I am working on a React JS project that is using React query, https://react-query.tanstack.com/, React hooks and functional components. But it is throwing error when I use react query for API call.
This is my component and how I use query within it.
const App = () => {
const [ list, updateList ] = useState([])
const info = useQuery(["item-list"], getList, {
retry: false,
refetchOnWindowFocus: false,
})
if (info.status == "success") {
updateList(info.data)
}
return (
//view components here
)
}
This is my getList API call logic
export const getList= async () => {
const { data } = await api.get("8143487a-3f2a-43ba-b9d4-63004c4e43ea");
return data;
}
When I run my code, I get the following error:
react-dom.development.js:14815 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
What is wrong with my code?
The main reason of that error here is you are running that code block in the
ifstatement in an infinite loop once you haveinfo.status === 'success'astrue. Then in every render theupdateListis called which triggers an another render.Probably I would use
useEffecthook here in order to listen for changes atinfoas:You should remove that
ifstatement from the body of<App />component and use theuseEffecthook instead as suggested above. By doing this thatifstatement will be checked onceinfois changing and not on every render.Suggested read is Using the Effect Hook.