javascriptreactjsswr

How to trigger loading state after data came once in SWR?


I have a table component just like in the image. There is a refresh button on right top. When user click it, I'm refetching the table by using mutate() but isLoading not becoming true so that loading spinner not showing. I want to make user know that table is refetching the data by showing the loading indicator.

My current line for fetching data:

const { data: originalData, isLoading, mutate } = useSWR(fetch-table, fetcher);

Table component:

enter image description here

Is there a way to make isLoading true after data came once?


Solution

  • There is a cache.delete feature in SWR. We need to delete cache to see the loading state again.

    import useSWR, { useSWRConfig } from 'swr';
        
    const { data: originalData, isLoading, mutate } = useSWR("fetch-table", fetcher);    
    const { cache } = useSWRConfig();    
    
    const onRefresh = () => {
      cache.delete("fetch-table") //fetch-table is your req key.
      mutate();
    }