Dealing with two different queryKeys that represent the same data #8606
Unanswered
Undistraction
asked this question in
Q&A
Replies: 1 comment
-
This seems to work, avoiding two requests up front, and allowing me to completely ignore the Edited to improve the below const useCopyProjectToCacheQuery = (project: Project) => {
const queryClient = useQueryClient()
return useQuery({
queryKey: [`project`, project?.id],
queryFn: async () => {
// Check the cache for data stored under the project's id
const projectDataById = await queryClient.getQueryData([
`project`,
project.id,
])
return isNil(projectDataById)
? // If the data isn't found, copy the data from the project's slug key
await queryClient.getQueryData([`project`, project.slug])
: // Otherwise get it from the server
await findProjectByIdAction(project.id)
},
enabled: isNotNil(project),
})
} Usage: const {
data: initialProject,
error: errorInitial,
} = useFindProjectBySlugQuery(slug)
const {
data: project,
error,
} = useCopyProjectToCacheQuery(initialProject) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have a couple of instances in my current project where I need to query by both an
id
and byslug
for the same resource, for example with queryKeys of['project', projectSlug]
and['project', projectId]
. The majority of times it isid
, but at the page roots, which use the URL slug, it'sslug
. I am unclear as to how I should deal with this issue as it has quite far-reaching implications, for example, if I perform a query somewhere else in the UI that also needs to update the resource, using['project', projectId]
this will not trigger the query that uses [project, projectSlug]
. Additionally, there are places where I usequeryClient.invalidateQueries
orqueryClient.cancelQueries
, or perform optimistic updates and these are also problematic for the same reason.One solution is to just update both queryKeys at the same time in all these instances, however this ends up triggering unnecessary requests and is a big maintenance burden.
This seems like it would be a common problem, but I haven't managed to find a satisfactory approach. Is there a nice way to deal with this issue, so that queries and mutations that use or manipulate either cacheKey can share the same data?
One solution I have considered is daisy-chaining
useQuery
So that the root query (using the slug) then triggers a second query which just pulls in the data from the cache and duplicates it.Beta Was this translation helpful? Give feedback.
All reactions