T
TanStack15mo ago
inland-turquoise

dependant queries router loading

GitHub
Dependent Queries · TanStack router · Discussion #922
Hey there, I'm currently looking at dependent queries using react-query. My use case is fetching items, each of which belonging to a group. I want to display the group name along with item data...
2 Replies
wise-white
wise-white15mo ago
So, based on the result you want to fetch another query? Why not await it in the loader and conditionally make a check?
export const Route = createFileRoute('/something')({
component: Items,
// Here I want to load 'getItemsQuery' first and then use its 'groupId' values to use with 'getGroupsByIdQuery' .. ?
loader: async ({ context: { queryClient } }) => {
const items = await queryClient.ensureQueryData(getItemsQuery)
// based on an if statement here, make a subsequent query
if (items === somethingelsehere) {
queryClient.ensureQueryData(getGroupsByIdQuery('123'))
}
},
});
export const Route = createFileRoute('/something')({
component: Items,
// Here I want to load 'getItemsQuery' first and then use its 'groupId' values to use with 'getGroupsByIdQuery' .. ?
loader: async ({ context: { queryClient } }) => {
const items = await queryClient.ensureQueryData(getItemsQuery)
// based on an if statement here, make a subsequent query
if (items === somethingelsehere) {
queryClient.ensureQueryData(getGroupsByIdQuery('123'))
}
},
});
If its completely dynamic, its a matter of creating an array of promises to await on.
const promises = []
const options = []

items.forEach(item => {
const opts = getGroupsByIdQuery('somethingdynamic')
options.push(opts)
promises.push(queryClient.ensureQueryData(opts))
})

await Promise.all(promises)
return { queryOptions }
const promises = []
const options = []

items.forEach(item => {
const opts = getGroupsByIdQuery('somethingdynamic')
options.push(opts)
promises.push(queryClient.ensureQueryData(opts))
})

await Promise.all(promises)
return { queryOptions }
inland-turquoise
inland-turquoiseOP15mo ago
so the query that I await queryCLient that thing I don't need to return right? perfect

Did you find this page helpful?