using return value of useQuery as a queryKey
This obviously does not work since
data is used before its declaration.
Is there a way to use data.id as a queryKey? I fetch the user by cookie information, so don't need to use an id, but want to use its id as a queryKey, so that if I fetch a user with useGetUserById function, which accepts an id, then I would hit the cache instead of making a request for the data I already have.7 Replies
extended-salmon•13mo ago
You can not self reference query data
For current user just use current_user as a key, or me
For users that you get by id you can get id from the query params
foreign-sapphireOP•13mo ago
That's the current setup I have, but I was thinking if I can add the userId here on the
current_user query, I would avoid making a request if I happen to fetch a user, which happens to be the current user, if that makes sense.extended-salmon•13mo ago
You can do it like this
It's overoptimization but here is how you can achieve this. You will have 2 records in the cache, one for a current user, and the second one for a user fetched by id. Technically speaking you should separate those, as those are 2 different concerns.
foreign-sapphireOP•13mo ago
Oh, that makes sense. Thanks!
extended-salmon•13mo ago
you're welcome 🙂
ratty-blush•13mo ago
Use a query Key factory, call the current user key factory with user ID from cookies.
ratty-blush•13mo ago
Effective React Query Keys
Learn how to structure React Query Keys effectively as your App grows