T
TanStack•10mo ago
itchy-amethyst

using return value of useQuery as a queryKey

export const useGetCurrentUser = () => {
const { data } = useQuery({
queryFn: () => query(),
queryKey: ['current_user', 'user', data.id],
});

return { user: data as UserResponse };
};
export const useGetCurrentUser = () => {
const { data } = useQuery({
queryFn: () => query(),
queryKey: ['current_user', 'user', data.id],
});

return { user: data as UserResponse };
};
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
sensitive-blue
sensitive-blue•10mo 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
itchy-amethyst
itchy-amethystOP•10mo 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.
sensitive-blue
sensitive-blue•10mo ago
You can do it like this
export const useGetCurrentUser = () => {
const queryClient = useQueryClient();

const { data: user } = useQuery({
queryFn: () => query(),
queryKey: ['current_user'],
});

if(user?.id) {
queryClient.setQueryData(['users', user.id], user);
}

return { user };
};

export const useGetUserById = (id?: number) => {
const { data:user } = useQuery({
queryFn: () => query(),
queryKey: ['users', id],
enabled: !!id
});

return { user };
};
export const useGetCurrentUser = () => {
const queryClient = useQueryClient();

const { data: user } = useQuery({
queryFn: () => query(),
queryKey: ['current_user'],
});

if(user?.id) {
queryClient.setQueryData(['users', user.id], user);
}

return { user };
};

export const useGetUserById = (id?: number) => {
const { data:user } = useQuery({
queryFn: () => query(),
queryKey: ['users', id],
enabled: !!id
});

return { user };
};
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.
itchy-amethyst
itchy-amethystOP•10mo ago
Oh, that makes sense. Thanks!
sensitive-blue
sensitive-blue•10mo ago
you're welcome 🙂
genetic-orange
genetic-orange•10mo ago
Use a query Key factory, call the current user key factory with user ID from cookies.
genetic-orange
genetic-orange•10mo ago
Effective React Query Keys
Learn how to structure React Query Keys effectively as your App grows

Did you find this page helpful?