Kristof Rado
Kristof Rado

Reputation: 881

Invalidate disabled query in react-query

I try to fetch data into a form using react-query.

It is disabled by default, because this form also handles empty forms (when no default values are loaded from server, ie.: it is a CREATE option).

It works correctly, but not in the best way. The cache will be there next time, so if I load the page again, the old data will be visible until the refetch() completes.

Is it somehow possible to remove from the cache when leaving the page? (It should always load as it is doing for the first time, when it does not have any cached data for this queryKey).

I have tried using queryClient.removeQueries(), but is seems to be not working, I assume it is because the query is in disabled state.

    const {data, isError, isSuccess, isFetching, isIdle, refetch} = useQuery(queryKey, getProject(id), {
        enabled: false,
        retry: 2,
    });

Upvotes: 2

Views: 9496

Answers (2)

Irvan Maulana Ahmad
Irvan Maulana Ahmad

Reputation: 1

in react-query v4 or above, you need to enable the query in order to invalidate the query.

for example:

const [filter, setFilter] = React.useState('')

const { data } = useQuery({
  queryKey: ["todos", filter],
  queryFn: () => fetchTodos(filter),
  // ⬇️ disabled as long as the filter is empty
  enabled: filter !== "",
})

// query invalidation only running as long as the query is enabled
// ⬇️ invalidate the query
queryClient.invalidateQueries({queryKey: ["todos"]})

Upvotes: 0

Kristof Rado
Kristof Rado

Reputation: 881

It seems that the right approach is to set cacheTime to 0.

Setting cacheTime to 0 will remove the query completely from the cache if React re-renders the page.

    const {data, isError, isSuccess, isFetching, isIdle, refetch} = useQuery(queryKey, getProject(id), {
        enabled: false,
        retry: 2,
        cacheTime: 0
    });

Upvotes: 8

Related Questions