How to use useQuery hook from ReactQuery to update state?

21.4k views Asked by At
import React, {useState, useEffect, Component} from 'react';
import {Grid, Paper, TextField} from '@material-ui/core'
import DataManager from './../data_manager/data_manager'

const dataManager = new DataManager();

const Tile = (props)=>{
    // Initializing State Variables
    const [state, setState] = useState({
        data : {}
    })

    const { status, data, error, isFetching } = useQuery("data",async()=>{
        const res = await fetch("localhost:8000");
        return res.json()
    }

    if(status==="success"){
        setState({data})
    }else{
        return(<p>Doing</p>)
    }
}

This code results in an infinite loop where the rendering keeps going on in a loop.

I think it is because setState causes useQuery to execute again setting the state again and so on.

Any help is appreciated. I want to store the data I get from useQuery in a state variable.

TIA.

2

There are 2 answers

0
Dennis Vash On BEST ANSWER

You might want to use useEffect as for now you fetch on every render:

const Tile = (props) => {
  const [state, setState] = useState({
    data: {},
  });

  const { status, data, error, isFetching } = useQuery("data", async () => {
    const res = await fetch("localhost:8000");
    return res.json();
  });

  useEffect(() => {
    if (status === 'success') {
      setState({ data });
    }
  }, [status, data]);

  return status === 'success' ? (
    <div>Success and use data</div>
  ) : (
    <div>Loading</div>
  );
};
2
Paul Moers On

You don't need to, it does that for you. A great video on React Query is https://www.youtube.com/watch?v=DocXo3gqGdI, where the part part is actually replacing a setup with explicit state handling by simply using useQuery.

Should you really want to set some state then a better way is to do it from the onSuccess callback. See https://react-query.tanstack.com/reference/useQuery.