How to wait for state changes before doing an refetch. #5720
-
Hello, I would like to ask for some advices. export const useGetRecordsQuery = ({ query, onSuccess, enabled }: { query?: FilterQuery, onSuccess?: (data: UserCompletedRoutineReport[]) => void, enabled?: boolean }) => {
return useQuery({
queryKey: [QueryKey.REPORTS],
queryFn: () => getReportsService(query),
onSuccess,
enabled
});
};
// Example how i use the custom hook
const { data, refetch } = useGetRecordsQuery({
query: { ...reportFilter, ...dateFilter },
enabled: false
}); I set enabled to false because i want to refetch the data manually (This is why i did not pass my query as a query key) when the user clicks a button to apply the filters and other to clear the filters. My problem starts with the clear filters because first I call a clearFilter function that set reportFilter and dateFilter to its initial values, but with this the values for reportFilter and dateFilter still being the old ones when the refetch its called const handleClearFilter = async () => {
clearFilter();
await refetch();
} If I add a Promise.resolve then the refetch it´s called with the cleared filters but I don´t think this is the way to do it const handleClearFilter = async () => {
clearFilter();
await Promise.resolve();
await refetch();
} I know that this isn´t a problem with RQ but me messing with the states so I´m looking for some advices if someone face something similar, thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
enabled:false + refetch opts out of what react-query wants to do, so I can't help much here. Calling The recommended solution is to:
pretty much what the |
Beta Was this translation helpful? Give feedback.
enabled:false + refetch opts out of what react-query wants to do, so I can't help much here. Calling
clearFilter
and thenrefetch
doesn't work because when you callrefetch
, your queryFunction still sees the closure with the old filters. It's like callingsetState
and then expecting the state to be updated, synchronously. That's just not how react works.The recommended solution is to:
pretty much what the
lazy query
example in the docs is doing: https://tanstack.com/query/v4/docs/react/guides/disabling-queries#lazy-queries