admin管理员组文章数量:1317565
I am working on a React JS project that is using React query, /, React hooks and functional ponents. But it is throwing error when I use react query for API call.
This is my ponent 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 ponents 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?
I am working on a React JS project that is using React query, https://react-query.tanstack./, React hooks and functional ponents. But it is throwing error when I use react query for API call.
This is my ponent 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 ponents 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?
Share Improve this question edited Oct 3, 2020 at 22:18 halfer 20.3k19 gold badges109 silver badges202 bronze badges asked Sep 30, 2020 at 13:37 Wai Yan HeinWai Yan Hein 14.9k43 gold badges211 silver badges423 bronze badges1 Answer
Reset to default 10The main reason of that error here is you are running that code block in the if
statement in an infinite loop once you have info.status === 'success'
as true
. Then in every render the updateList
is called which triggers an another render.
Probably I would use useEffect
hook here in order to listen for changes at info
as:
useEffect(() => {
if (info.status == "success") {
updateList(info.data)
}
}, [info])
You should remove that if
statement from the body of <App />
ponent and use the useEffect
hook instead as suggested above. By doing this that if
statement will be checked once info
is changing and not on every render.
Suggested read is Using the Effect Hook.
本文标签:
版权声明:本文标题:javascript - React Query with hooks is throwing error, "Uncaught Error: Too many re-renders. React limits the number of 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742021092a2414686.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论