reactjsreact-query

React Query invalidate query not working on onSuccess


I want to use invalidate queries but it doesnt fetch it or trigger it.

I have a dashboard and I am on the user screen on the navigation. I mutate from the user screen an action and want to refrech the dashboard which is in other file.

user: (Here on onSuccess is the invalidateQueries thats not trigger)

  const {
    isPending,
    mutate
  } = useMutation({
    mutationKey: ["SETTINGS"],
    mutationFn: async (params: TMutateSettingsParam) => {
      console.log(params);
      const res = await axiosPrivate.post(`${URL}/auth/deleteAccountByAdmin`, params, {
        headers: headersJSON,
        withCredentials: true
      });

      const data: IReturnApi<null> = res.data;

      return data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({queryKey: ['dashboard']})
      toast.success(data.message);
    },
    onError: (err: AxiosError<IReturnApi<IValidationError[]>>, _variables) => {
      if(err.response) {
        toast.error(err.response.data.message);
      } else {
        toast.error('Es ist ein Fehler aufgetreten. Bitte wenden Sie sich an den Support.');
      }
    }
  });

Here is my app.tsx

export const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <BrowserRouter>
      <QueryClientProvider client={queryClient}>
        <AuthProvider>
          <App />
        </AuthProvider>
      </QueryClientProvider>
    </BrowserRouter>
  </React.StrictMode>,
)

And here is my dashboard query which I want to invalidate:

  const { 
    isLoading,
    isError,
    data,
    error
  } = useQuery({
    queryKey: ['dashboard'],
    refetchOnWindowFocus: false,
    queryFn: async () => {
      const res = await axiosPrivate.get(`${URL}/dashboard/getAll`, {
        headers: headersJSON,
        withCredentials: true
      });
    
      const data: IDashboardData = await res.data;
      return data;
    }
  });

What I am doing wrong ?


Solution

  • I think if you should use queryClient.refetchQueries() like describe here. But to work properly, make sure you set the useQuery staleTime to a value greater than 0. For example 5*1000.

    So on your user page, you can do a queryClient.refetchQueries({queryKey: ['dashboard']}) and when you arrive on the dashboard, no new requests will be made.

    By default, the staleTime which indicates whether the data is still valid is set to zero. If you don't change it, you'll get a fetch using queryClient.refetchQueries() and another fetch when you load the page.

    You can read this guide that describe all important thing to know about tanstack query and staleTime : docs