Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/65929869/react-query-is-there-a-callback-that-get-trigger-regardless-of-whether-getquery

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...