I have a query that uses placeholderData: keepPreviousData. This means the
query is in a hard loading state, with no placeholder data, on initial mount.
Then, when the queryKey changes, it goes into a 'soft' loading state:
placeholder data shown, isPlaceholderData=true and isLoading=false.
My component looks like this:
const exampleQ = useQuery({
queryKey: ['example'],
queryFn: example,
placeholderData: keepPreviousData,
});
if (exampleQ.isLoading) {
return (
<div>
hard loading state, no placeholder data to display. big spinner here.
</div>
);
} else if (exampleQ.isSuccess) {
return (
// Show outdated data with overlay if isPlaceholderData. Otherwise just display the data.
// If a background refresh (isRefetching) is happening, we show the
// current data with no indication to the user.
<div className={exampleQ.isPlaceholderData ? 'overlay' : ''}>
Data: { exampleQ.data }
</div>
);
}
Now, somewhere far away in the component tree, I need to put exampleQ back into
the soft loading state, with isLoading=false, isPlaceholderData=true. I then
wait some time for something unrelated. When ready, I want the query to refetch
and continue to display the placeholderData while refetching.
const queryClient = useQueryClient()
async function onUpdate() {
queryClient.putBackToSoftLoading(['example']); // trigger soft loading, does this method exist?
await doSomething(); // async waiting. overlay and keepPreviousData showing during this time.
queryClient.triggerFetchWhileKeepingPlaceholder(['example']) // trigger refetch whie staying in soft loading.
}
I've tried every combination of QueryClient methods that I can think of and none of them put the query back to the soft loading state in a way that I can tell the difference between that and background refreshes. What is the right way to accomplish this? Am I going about this the wrong way, and there's some other React way that I should be communicating between this components other than react-query?
- resetQueries goes back to hard loading instead of soft, and also sends out the request before I'm ready.
- refetchQueries doesn't set
isPlaceholderData=trueso my component can't tell if its background refetching or or not. - fetchQuery gives me no way to set
isPlaceholderData=true