T
TanStack12mo ago
ambitious-aqua

should I use getQueryData in this use case?

Hey, I have multiple calls to a same useQuery hook, I have set a staletime to 5000ms because I need to refecth the data sometimes, but in one place of my app, I only want to get the data from the cache without fire an api call no matter what (even if the data is stale), I know that some data will be in the cache when I reach this point, should I use getQueryData in that case?
8 Replies
yelping-magenta
yelping-magenta12mo ago
If you fetch the data, render and then the data updates in the cache you wont be notified. If you need that you could use an useQuery with enabled: false.
ambitious-aqua
ambitious-aquaOP12mo ago
Yes I don't want to update the data in that place even if the data is stale and has been updated I just want to retrieve the data from the cache
yelping-magenta
yelping-magenta12mo ago
yeah, my point is that, if you have another useQuery somewhere, that updates the cache, you will have old cache data
ambitious-aqua
ambitious-aquaOP12mo ago
do you mean: queryClient.getQueryData(['key']) is exactly the same as useMyData({enabled: false}) ? that's not what I want, I want to be up to date with the current cache
yelping-magenta
yelping-magenta12mo ago
not really, queryClient.getQueryData will only get the data from the cache once ran, if the cache data changes it will not update (unless reran, i.e. if your component rerenders because props changed, but you should not rely on that), useMyData({ enabled: false }) will subscribe to the cache, if another query updates the cache data, the data property will change with the new cache value enabled just tells it not to execute the queryFn, but it will subscribe to the cache value, and will update if the cache value changes
ambitious-aqua
ambitious-aquaOP12mo ago
ok ok it's pretty much the same even if your component does not rerender (if you call the getQueryData at the root of the component) ok ok I should use useQuery if I understand well should I?
yelping-magenta
yelping-magenta12mo ago
depends on what you want, but as far as I got it, you want useQuery. Quick recap - getQueryData gets the data from the cache at the moment the function was called, no further updates if the cache data changes - useQuery({ enabled: false }) gets the data from the cache and subscribes, so when the cache data changes, the query.data changes too with the new value react terminology would be that getQueryData is not reactive, as in, it does not trigger a rerender of your component
ambitious-aqua
ambitious-aquaOP12mo ago
ok ok thank you for your explanation!

Did you find this page helpful?