How key composition works
masterYou can compose complex query keys by combining existing keys. To use a key's underlying array for composition, call the key function with its arguments and then invoke it with an extra set of parentheses () to retrieve the array.
const postKeys = defineQueryKeys("post", {
detail: key((postId: string) => ["post", "detail", postId]),
});
const extendedPostKeys = defineQueryKeys("post.extended", {
withAuthor: key((postId: string, authorId: string) => [
...postKeys.detail(postId)(), // Note the extra () to get the array
"author",
...userKeys.profile(authorId)(),
]),
});
// Result: ["post", "detail", "123", "author", "user", "profile", "456"]const postKeys = defineQueryKeys("post", {
detail: key((postId: string) => ["post", "detail", postId]),
});
const extendedPostKeys = defineQueryKeys("post.extended", {
withAuthor: key((postId: string, authorId: string) => [
...postKeys.detail(postId)(),
"author",
...userKeys.profile(authorId)(),
]),
});