T
TanStack5w ago
equal-aqua

Project structure with a global loading gate (data is required to be available after a point)

I'm working on a NextJS (app router) project and what I want is that, if the user accesses certain pages within the app (those pages would be grouped using a next layout group), certain pieces of data/queries are always available. I apologize in advance for complicating things with nextjs. By that I mean that I can use those queries without checking the "isPending"/"isLoading" properties on the query, I just need to be certain that they are available and for typescript not to complain. What would be the right way to structure my code for this? There is a prefetching example on the docs (https://tanstack.com/query/v5/docs/framework/react/examples/nextjs-app-prefetching) but I guess I will still need to check loading states with this right (typescript won't be happy at least). Should I use useSuspenseQuery and Suspense for my use case? Here is how I thought the code might be structured: layout.tsx - this file is in the layout group for pages that need data to be available
"use client";
export default function LayoutDataGate({ children }) {
return (
<SomeProvider>
<Suspense fallback={<Spinner />}>
<LoadingGate>
{children}
<LoadingGate />
</Suspense>
</SomeProvider>
)
}

function LoadingGate({ children }) {
// this just fires the useSuspenseQueries for the children

useSuspenseQuery(someQueryOptions1);
useSuspenseQuery(someQueryOptions2("username"));
useSuspenseQuery(someQUeryOptions3);

return children
}
"use client";
export default function LayoutDataGate({ children }) {
return (
<SomeProvider>
<Suspense fallback={<Spinner />}>
<LoadingGate>
{children}
<LoadingGate />
</Suspense>
</SomeProvider>
)
}

function LoadingGate({ children }) {
// this just fires the useSuspenseQueries for the children

useSuspenseQuery(someQueryOptions1);
useSuspenseQuery(someQueryOptions2("username"));
useSuspenseQuery(someQUeryOptions3);

return children
}
Does this make sense?
2 Replies
equal-aqua
equal-aquaOP5w ago
The goal is for the children of the layout to be able to freely access data from someQueryOptions1/2/3 without worrying about the data being pending or errors, but I can still use react-query stuff like staleTime, invalidation, refetchInterval etc
vicious-gold
vicious-gold5w ago
yeah this is a good use-case for suspense imo

Did you find this page helpful?