T
TanStack3y ago
correct-apricot

How to properly use query key factories with multiple variable keys?

I essentially have a query that looks like this:
export default function usePost(params) {
return useQuery(["post", params.sessionId, params.dataId, params.postId], () => getPostById(postId));
}
export default function usePost(params) {
return useQuery(["post", params.sessionId, params.dataId, params.postId], () => getPostById(postId));
}
What is the best way to create a query key factory object for this? I may want to access posts based on sessionId only, or postId, or even just dataId (e.g. perhaps to invalidate in order to refetch, etc..). I was thinking of something like this but not sure if this actually makes sense especially since each key in my queryKey object seems to depend on the previous. Curious on others' thoughts on this. Also any suggestions to the naming convention for the items in the queryKeys object?
const queryKeys = {
all: ['post'] as const,
sessionId: (sessionId: string) => [...querykeys.all, id] as const,
categoryId: (sessionId: string, categoryId: string) => [queryKeys.sessionId(sessionId), categoryId]
postId: (sessionId: string, categoryId: string, postId: string) => [...categoryId.categoryId(sessionId, categoryId, postid)] as const
}
const queryKeys = {
all: ['post'] as const,
sessionId: (sessionId: string) => [...querykeys.all, id] as const,
categoryId: (sessionId: string, categoryId: string) => [queryKeys.sessionId(sessionId), categoryId]
postId: (sessionId: string, categoryId: string, postId: string) => [...categoryId.categoryId(sessionId, categoryId, postid)] as const
}
And then would I plug this into my useQuery hook with the following?
export default function usePost(params) {
return useQuery([queryKeys.postId(sessionId, categoryId, postid)], () => getPostById(postId));
}
export default function usePost(params) {
return useQuery([queryKeys.postId(sessionId, categoryId, postid)], () => getPostById(postId));
}
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?