Miremad Bagheri
Miremad Bagheri

Reputation: 11

Tanstack/react-query v5 - Invalidating or refetching inactive query

Im using Tanstack/react-query v5.12.2 and I need to invalidate or refetch an inactive query using useQueryClient(), but I think there is something changed in v5. I even set type to "inactive" or "all", but it is not working. when enable property is "true", it works but i need to set enable false. any idea?

Example.tsx

import { useQuery, useQueryClient } from '@tanstack/react-query';
export function Example() {
  const qc = useQueryClient();
  const { isLoading, error, data } = useQuery({
    queryKey: 'repoData',
    queryFn: () => {
      return fetch(
        'https://api.github.com/repos/tannerlinsley/react-query'
      ).then((res) => res.json());
    },
    enabled: false,
  });

  if (!data) {
    return (
      <button
        type="button"
        onClick={() =>
          qc.resetQueries({ queryKey: 'repoData', type: 'inactive' })
        }
      >
        Click to refetch all queries
      </button>
    );
  }

  if (isLoading) return 'Loading...';

  if (error) return 'An error has occurred: ' + error.message;

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.description}</p>
      <strong>👀 {data.subscribers_count}</strong>{' '}
      <strong>✨ {data.stargazers_count}</strong>{' '}
      <strong>🍴 {data.forks_count}</strong>
    </div>
  );
}

App.tsx

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

const queryClient = new QueryClient();
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Example />
    </QueryClientProvider>
  );
}

export default App;

I tried it with v4 and it was ok, but in v5 it's not working.

Upvotes: 0

Views: 1124

Answers (1)

jakekh
jakekh

Reputation: 19

you need to do this:

queryClient.invalidateQueries({
    queryKey: ["Your-Key"],
    refetchType: "all"//here you can specify "active", "inactive" or "all"
});

https://tanstack.com/query/v5/docs/reference/QueryClient/#queryclientinvalidatequeries

Upvotes: 0

Related Questions