react-query: is there a callback that get trigger regardless of whether getQuery is cached or not?

Viewed 2417

I want to do some side effects like setState and update context after the data is fetched. However, the onSuccess will not be executed when the data is in cache. Also useEffect doesn't work because if the data is cached, it doesn't change from undefined to the real data. Therefore it doesn't get trigger either. What's the best way of doing this? Thanks

1 Answers

My usecase is to extract some values from the data returned from useQuery and set a new state on those.

usually, they’re shouldn’t be a need to be a need to copy state from react-query into local state. This will just lead to duplication of the source of truth. It is best to keep them separated, so that you can also profit from background updates.

If you want to transform the data or subscribe to parts of the data, use the select option of useQuery:

const { data } = useQuery(key, fn, { select: data => data.map(...) })

Alternatively, you can compute some new data depending on the returned data with useMemo, e.g.:

const { data } = useQuery(...)

const articles = useMemo(() => data?.map(...), [data])
// work with articles from here on

You can also put that nicely in a custom hook.

Related