I have two views when fetching:
I'm using status === 'pending'
for detecting whether data is fetching.
Is there a way to check if I'm fetching data for the first time?
i.e. when I'm fetching for 2nd time it's definitely coming from filters and I need to display a different view.
No need to use useRef. An easy way to achieve this is using keepPreviousData
import { useQuery, keepPreviousData } from '@tanstack/react-query';
//...
const { data, isPlaceholderData, status, error } = useQuery({
queryKey: [‘component’, params, onSuccess],
queryFn: () => fetchData(params, onSuccess),
enabled,
placeholderData: keepPreviousData,
staleTime: 0
});
//...
return (<div>
<header>This element will be visible when you fetch data again</header>
{isPlaceholderData
? <Loading>
: <div>Your data ({data}) will be displayed here</div>
}
</div>);
When using placeholderData
and keepPreviousData
, then the data remains populated when a new fetch is happening due to the query key changing. And isPlaceholderData
can be used to to show the loading UI during that time.