-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Closed as not planned
Closed as not planned
Copy link
Labels
bugSomething isn't workingSomething isn't workinghas workaroundhelp wantedExtra attention is neededExtra attention is neededpackage: query-corewontfixThis will not be worked onThis will not be worked on
Description
Describe the bug
When useQueries is used with an empty array [] for queries, the combine function will return a new instance each time the component carrying the hook is rendered. This can cause loop-rendering issues. It is possible to end up with an empty array for queries when the queries are determined dynamically. For instance:
export const useGetDevices = ({ ids }: { ids: string[] }) => {
return useQueries({
// queries are dynamically determined from the given ids
// when ids is empty, queries will be []
queries: ids.map((id) => {
return {
queryKey: ["get-device", id],
queryFn: async () => getDevice(id)
};
}),
combine: (results) => {
// here we simply reduce the results into a Record
// when ids is not empty the reduced record will be the same instance each time
// but when ids is empty the reduced record will be a new instance of an empty object each time
return results.reduce<Record<string, Device[]>>((acc, result) => {
const { data } = result;
if (!data) return acc;
return {
...acc,
[data.id]: data.content,
};
}, {});
}
});
};More details in this discussion
Your minimal, reproducible example
https://codesandbox.io/s/react-query-combine-empty-array-7n29nr?file=/src/useGetDevices.ts:523-773
Steps to reproduce
- In app.tsx: set
idsto a non-empty array (for instance["1"]) - Click on "render" with the console opened
- See that the useEffect
devicesRecord changedis NOT called when the component is rendered - Edit app.tsx to set
idsto an empty array[] - Click on "render" again
- See that now the useEffect is called each time the component is rendered
Expected behavior
The useEffect should not be triggered each time the component is rendered
How often does this bug happen?
Every time
Screenshots or Videos
No response
Platform
- OS: macOS
- browser: chrome, FF
Tanstack Query adapter
react-query
TanStack Query version
5.8.3
TypeScript version
No response
Additional context
No response
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't workinghas workaroundhelp wantedExtra attention is neededExtra attention is neededpackage: query-corewontfixThis will not be worked onThis will not be worked on