6
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 Answers 2

8

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>
  );
};
4

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.

2
  • 9
    there are cases where it is required e.g. you use useQuery to get the initial set of data (an array of records), then you let user to partially edit them. You would need to place this on a state to show for example fields that were edited etc before the actual saving... Commented Oct 11, 2022 at 14:29
  • 3
    These callbacks have been deprecated and will be removed in version 5: tkdodo.eu/blog/breaking-react-querys-api-on-purpose useEffect is recommended Commented Aug 10, 2023 at 3:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.