Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react query invalidateQueries cache

Tags:

react-query

function Dashboard(): ReactElement {
    const queryClient = useQueryClient();
    const getDashboard = async () => {
        // Logic to fetch dashboard data
    };
    
    const { data, isLoading } = useQuery(['dashboard'], getDashboard);
    
    const onClick = () => {
        // db dashboard data update logic
        queryClient.invalidateQueries(['dashboard']);
    }

    if (isLoading) {
        return <div>Loading</div>;
    }

    return (
        <div>
           <button onClick={onClick}>update dashboard</button>
           {data?.map((card) => <Panel {...card} />)}
        </div>
    );
}

function Panel(props: IPanel): ReactElement {
    const getApiData = async (props.id) => {
        // Logic to get user-selected api data
    };

    const { data, isLoading } = useQuery(['dashboard'], getApiData);

    if (isLoading) {
        return <div>Loading</div>
    }

    return (
        <div>
            <InnerComponent {...data}>
        </div>
    );
}

When I have this kind of code, I want to update the dashboard data when I press the button, blow the dashboard cache data using queryClient, and then do a refresh. After being passed to the Panel component, when the dashboard data is updated, it is passed back to the Panel component and the getApiData function is executed twice in the Panel component.

Changing the stalTime and cacheTime did not solve the problem.

like image 227
raccoon_ko Avatar asked Sep 11 '25 03:09

raccoon_ko


1 Answers

What I want is when I run queryClient.invalidateQueries(['dashboard']) it starts with dashboard and all subqueries are refetched. But when invalidates is executed, it returns the cached data (past data) before getting the updated data and then returns the updated data again. Since staleTime is also 0, shouldn't the cache data be invalidated if queryClient.invalidateQueries is executed? But I don't know why it keeps returning the previous data first

React Query will never remove data from the cache, unless it's for garbage collection (removing Queries that have been unused for some time). The reasoning is that any data, even stale one, is preferred to a full blown loading spinner.

Invalidation just marks queries as stale, and will then refetch active queries that are stale. What you are looking for sounds like queryClient.resetQueries, which will:

  • reset Queries back to their initial state, most likely undefined, this blowing data away
  • and then it will refetch active queries.

You will wind up with a hard loading state then, but if that's what you want, that's the method you're looking for.

like image 53
TkDodo Avatar answered Sep 13 '25 18:09

TkDodo