T
TanStack•16mo ago
conscious-sapphire

Unique key based on data

Hello! I have the following problem: I want to output the user id as a query key. But I only get the id from the query function. Is this possible, and if so, how?
const { data: user, status: userStatus } = useQuery({
queryKey: ['users', user.id],
queryFn: async () => await getCurrentUserWithRelations(),
})
const { data: user, status: userStatus } = useQuery({
queryKey: ['users', user.id],
queryFn: async () => await getCurrentUserWithRelations(),
})
7 Replies
exotic-emerald
exotic-emerald•16mo ago
It's impossible. I would use ['currentUser'] as a key instead. This key structure ['users', user.id] may be used for any other user in the system, but you must know id beforehand.
conscious-sapphire
conscious-sapphireOP•16mo ago
But if the same key is used, you run the risk of incorrect data being displayed for other users due to the cache, right? So I see the only possibility in a server component to initially get the user and use this data from it as userId and initalData.
exotic-emerald
exotic-emerald•16mo ago
One way or another on logout you should clear the RQ cache to prevent incorrect data displayed to a newly logged-in user. I assume getCurrentUserWithRelations returns a currently logged-in user right?
conscious-sapphire
conscious-sapphireOP•16mo ago
Yes based on the session (Lucia Auth) it fetches the currently logged in user. But if two users are logged in at the same time and use the same key, it shows the same user for all of them, doesn't it?
exotic-emerald
exotic-emerald•16mo ago
nope Each user is logged in on his own pc with his own instance of your app. They simply cannot intersect The only time when there may be collisions is when 2 users both use the same pc to work with an app. After 1 user is logged out you must clear the cache, so after the 2nd logs in he may start from scratch. This prevents cache leaks from 1 session to the 2 session. Other than that every user works with its own instance of the app, even if you try to log in 2 different users simultaneously in 2 different tabs, you will see that ['currentUser'] has different user data in each tab.
conscious-sapphire
conscious-sapphireOP•16mo ago
Then I misunderstood. I will do this with the currentUser key. Thank you!
exotic-emerald
exotic-emerald•16mo ago
you're welcome 🙂

Did you find this page helpful?