0

React Query has a useful hook called useIsFetching (see docs), which allows checking whether a given query is currently fetching data, like so:

const queryCount = useIsFetching(['my-query-name'])

I want to do something very similar: I want to know for a given endpoint, if data has already been fetched (isFetched).

I know this is returned from the useQuery hook, but using this hook would call the endpoint again, and I want to avoid the repeated call.

Any ideas how to achieve this?

2 Answers 2

1

You can avoid calling the endpoint again by setting a staleTime on your query, because in that time, data will come from the cache only.

if data doesn't exist yet, it will be fetched. If you don't want that, consider queryClient.getQueryState(['my-query-name']). However, this will not create a subscription, so your component will not re-render if the query state changes.

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

2 Comments

Thanks for these suggestions. Unfortunately staleTime won't help in my case, because sometimes I will need to check the query status before the query has even run. The second suggestion is interesting, but like you said, it doesn't cause the component to re-render on change, so it's not adequate.
two workarounds: useQuery() with enabled: false if you just need to check + subscribe to the result; or you call useIsFetching(key) just to get a re-render when the queries fetching status changes, and then use getQueryState. I like the first option better, as the second one will not inform you of updates done via queryClient.setQueryData for example....
1

Solved by utilizing useQuery's enabled property, which allows defining whether or not to make the request.

useQuery(
    ['my-query-name', requestPayload],
    () => callMyEndpoint(requestPayload),
    {
        // ...
        enabled: booleanToIndicateWhetherToEnable,
    }
)

Comments

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.