Home > Enterprise >  react-query fetched data to useState causing error
react-query fetched data to useState causing error

Time:08-10

I'm trying to assign the data fetched through useQuery to a state to handle a better conditional rendering based on if the request is empty or not.

At the moment, what I'm trying to do looks like the following:

...
const [userLists, setUserLists] = useState({});
...
const lists = useQuery(["lists"], api.fetchLists);

  if(lists.isLoading){
    //
  } else {
    setUserLists(lists.data.lists); // this line is causing the issue
  }

The browser is returning me a Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Why would this happen? How is it possible to actually put the result in a useState hook?

CodePudding user response:

So this is causing an infinite loop because you are setting state inside the component. To prevent this please use useEffect like this:

const [userLists, setUserLists] = useState({});
...
const lists = useQuery(["lists"], api.fetchLists);

useEffect(() => {
    if (lists.isLoading) {
        // any loading state you might have
    } else {
        setUserLists(lists.data.lists); // this line is causing the issue
    }
}, [lists])

CodePudding user response:

Your component goes into the loop because you are checking for the loading state first and setting the state in the else block.

Therefore, else block gets calls multiple times. Which causes the Too many re-renders

try the following code

     ...
    const [userLists, setUserLists] = useState({});
    ...
    const lists = useQuery(["lists"], api.fetchLists);

    if(lists.isLoading){
      // set loading here or render loading component
    }

    if(!lists.isLoading && !lists.error){
      setUserLists(lists.data.lists); // this line is causing the issue
    } 
  • Related