Primary Key should accepts arrays
Closed this issue · 2 comments
MiltonAkash commented
We manage a heirarchy of things like below so invalidating becomes easier. React query kit is awesome but the primary key being a string prevents implementation of heirarichal key thing. Should we add or any other workaround ???
const todoKeys = {
all: ['todos'] as const,
lists: () => [...todoKeys.all, 'list'] as const,
list: (filters: string) => [...todoKeys.lists(), { filters }] as const,
details: () => [...todoKeys.all, 'detail'] as const,
detail: (id: number) => [...todoKeys.details(), id] as const,
}
liaoliao666 commented
There are no plans to accept arrays as primaryKey, but you can implement it as belown. This is also very simple.
const postScope = 'posts:'
const usePostList = createQuery({
primaryKey: `${postScope}list`
})
const usePostDetail = createQuery({
primaryKey: `${postScope}detail`
})
// invalidate all queries within post scope
queryClient.invalidateQueries({
predicate(query) {
return query.queryKey[0].startWidth(postScope)
},
})
liaoliao666 commented
Or organize queries in a object.
const postQueries = {
useList: createQuery({
primaryKey: `posts:list`,
}),
useDetail: createQuery({
primaryKey: `posts:detail`,
}),
}
Object.values(postQueries).forEach(fn =>
queryClient.invalidateQueries({ queryKey: fn.getKey() })
)
``