1

I am trying to learn react.js with @tanstack/react-query and so far things are working fine.

However, I am trying to use invalidateQueries to clear the existing cache after insert, update, etc. to fetch the fresh data from the server. But, its not working.

I have already tried various solutions found after googling, but still not success.

main.tsx

import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
...

const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            staleTime: 10 * (60 * 1000), // 10 mins
            refetchOnMount: false,
        },
    },
});

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

edit.tsx

const update = async (data: any) => {
    ...
};

export default () => {
    const queryClient = useQueryClient();

    ...

    const { mutate, isLoading } = useMutation({
        mutationFn: update,
        onError: ({ response }) => setErrors(showErrors(response.data)),
        onSuccess: () => {
            queryClient.invalidateQueries([modules.accountTypes.cacheKey]);

            navigate(PATH);
        },
    });

    ...
};
4
  • could you share the query you wrote for fetching/mutating data with key modules.accountTypes.cacheKey Commented Mar 14, 2024 at 11:05
  • modules.accountTypes.cacheKey = 'accountTypes' Commented Mar 14, 2024 at 11:06
  • are you sure that you used the same key for the query also? Commented Mar 14, 2024 at 11:31
  • Absolutely, already verified several times Commented Mar 14, 2024 at 11:49

1 Answer 1

1

I tried your code using @tanstack/react-query v5 and It worked. Here is the code I tested:

Query

function MyQuery() {
  const { isLoading, isError, error, data } = useQuery({
    queryKey: ["accountTypes"],
    queryFn: () =>
      fetch("https://jsonplaceholder.typicode.com/posts?_limit=5").then(
        (res) => {
          console.log('Query is called.');
          return res.json();
        }
      ),
  });

...

Mutation

function MyMutation() {
  const queryClient = useQueryClient();

  const navigate = useNavigate();

  const { isPending, isError, error, data, mutate } = useMutation({
    mutationFn: () =>
      fetch("https://jsonplaceholder.typicode.com/photos?_limit=5").then(
        (res) => res.json()
      ),
    onError: ({ response }) => setErrors(showErrors(response.data)),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["accountTypes"] });
      navigate("/my-path");
    },
  });

...

You can also try making onSuccess an async function, put await before queryClient.invalidateQueries and see what happens.

Sign up to request clarification or add additional context in comments.

8 Comments

My react-query version is 4, let me try on 5.
If you want to stick to the v4, Adding return before the invalidate function may also help. Saw this as a solution in another question.
Ok, could you please post the link of that question..? So I can have a look.
Here you are: link
Thank you @Amirreza. I looked at the posted link and though, adding return may provide the solution, it will also prevents the redirection code from executing, written after. Therefore, I chose to upgraded from v4 to v5 and it worked. Many thanks again..:)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.