Search code examples
react-hooksfetchreact-querytanstackreact-query

react-query: Detect first first fetch


I have two views when fetching:

  1. Initial one, when you see a component for the first time.
  2. When you changed filters inside this component, so header inside should be displayed and content at the bottom should show spinner.

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.


Solution

  • 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.

    Live demo of separate loading UIs