T
TanStack•4w ago
automatic-azure

how to send queryClient's cache to the client?

so let's say i have a route like this
export const Route = createFileRoute('/user/$userId/friends')({
loader: async ({ context: { queryClient }, params }) => {
const list = await queryClient.ensureQueryData(getUserFriendsQuery({
userId: Number(params.userId),
page: 1,
}))
return {
list,
}
},
component: RouteComponent,
})
export const Route = createFileRoute('/user/$userId/friends')({
loader: async ({ context: { queryClient }, params }) => {
const list = await queryClient.ensureQueryData(getUserFriendsQuery({
userId: Number(params.userId),
page: 1,
}))
return {
list,
}
},
component: RouteComponent,
})
and the queryFn inside my getUserFriendsQuery looks something like this:
const PER_PAGE = 100
export function getUserFriendsQuery(options: {
userId: number
page: number
}) {
return {
queryKey: ['friends', options],
queryFn: async (ctx: QueryFunctionContext) => {
const response = await callSomeServerFn({
data: { limit: PER_PAGE, offset: options.page * PER_PAGE },
signal: ctx.signal,
})
// response: { items: FriendRelation[], users: UserInfo[] }
for (const user of response.user) {
ctx.client.setQueryData(['user', user.id], user)
}
return response.items
},
}
}
const PER_PAGE = 100
export function getUserFriendsQuery(options: {
userId: number
page: number
}) {
return {
queryKey: ['friends', options],
queryFn: async (ctx: QueryFunctionContext) => {
const response = await callSomeServerFn({
data: { limit: PER_PAGE, offset: options.page * PER_PAGE },
signal: ctx.signal,
})
// response: { items: FriendRelation[], users: UserInfo[] }
for (const user of response.user) {
ctx.client.setQueryData(['user', user.id], user)
}
return response.items
},
}
}
so i populate the query cache of the queryClient while fetching the friends list so that i have a single store for all server-side user entities, that i can access by simply calling useQuery(getUserQuery(123)) (i.e. useQuery({ queryKey: ['user', 123], queryFn: ... }) however this doesn't seem to play well with tanstack start, since only the result of the loader function is sent to the client, and the queryClient cache is not, leading to n+1 extra requests from the client, since the client doesn't know anything about the users so the question is: what would be the best way to implement sending the queryClient cache to the client? is there maybe something ready-made for this? (though haven't found anything in the docs) or maybe there's another recommended way to handle server entities in tanstack query+start and i'm just doing everything wrong? :D
1 Reply
automatic-azure
automatic-azureOP•4w ago
actually nevermind i somehow missed the setupRouterSsrQueryIntegration in the solid-query example 😭

Did you find this page helpful?