How to refresh credentials that are used within queryFn without making them part of the cacheKey?
I have a scenario where credentials need to be refreshed every x minutes for subsequent requests to succeed.
Currently the queryFn uses old cached credentials despite the react state containing the updated credentials. I assume queryFn is using some memorisation in some fashion internally. How do I ensure refetches use the latest credentials instead of the initial ones that have now expired? I don't want to add the credentials to the cacheKey as it will unnecessarily invalidate existing long lived cache data.
Currently the queryFn uses old cached credentials despite the react state containing the updated credentials. I assume queryFn is using some memorisation in some fashion internally. How do I ensure refetches use the latest credentials instead of the initial ones that have now expired? I don't want to add the credentials to the cacheKey as it will unnecessarily invalidate existing long lived cache data.
6 Replies
absent-sapphire•3y ago
Who wrote the queryFn? I’ve never had an issue with this and I typically use tokens that expire every few minutes…
ambitious-aqua•3y ago
Pretty likely a stale closure problem. Please show some code. One way would be to put the token in a ref instead
harsh-harlequinOP•3y ago
Its a fairly complicated example, so difficult to setup a sand box, but here it is:
I have the following hook:
If I add the integration credentials (or a hash of them) to the cache key then it fixes the problem. But this is obviously undesirable as I then unnecessarily refetches all the queries.
sunny-green•3y ago
Does
integration receive a new reference or is it just mutated? If just mutated it wouldn't trigger useMemo to refresh. Does it work if you remove useMemo (for testing)?ambitious-aqua•3y ago
useMemo is not the problem. it also doesn't do anything meaningful, so it could be safely removed.
if integrations is react state, then it should be part of the queryKey.
if it's just a token, then the question is: why is it part of the react lifecycle? is your component re-rendering if the credentials change?
as I said, you can put them in a useRef and update them, then access them with .current in the queryFn to bypass it. But the better solution would be to take things that shouldn't re-render your component or re-run your queryFn out of the react lifecycle altogetherharsh-harlequinOP•3y ago
Ok thanks,
I think this makes sense.
The integration contains other data which does need to cause a render. hence why it was inside.
I'll look into separating the two, to keep them seperate
Thanks for your responses!