T
TanStack5mo ago
magic-amber

need access to response of endpoint before any route

The structure of my app is -
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
function RootComponent() {
return (
<AuthProvider>
<>
<Outlet />
<TanStackRouterDevtools position="bottom-right" />
</>
</AuthProvider>
);
}
function RootComponent() {
return (
<AuthProvider>
<>
<Outlet />
<TanStackRouterDevtools position="bottom-right" />
</>
</AuthProvider>
);
}
In my AuthContext, I need access to the response of my /sessions endpoint on the initial load. So, in my root , I have - ``` export const Route = createRootRouteWithContext<RouterContext>()({ component: RootComponent, beforeLoad: async ({ context }) => { try { const queryClient = context.queryClient; const data = await queryClient.ensureQueryData(["sessions"], getSessions); if (!data) { throw redirect({ to: "/login" }); } } catch (error: any) { console.log("error", error); // if (error) { // throw redirect({ to: "/login" }); // } // if (error.response?.status !== 401) { // throw error; // } else { // // throw redirect({ to: "/login" }); // } } console.log("afterLoad"); }, errorComponent: () => <div>Error in root.tsx</div>, pendingComponent: () => ( <div className="flex justify-center items-center h-screen"> Loading sessions... </div> ), }); ```
2 Replies
magic-amber
magic-amberOP5mo ago
Then, in my AuthContext, I have -
export function AuthProvider({ children }: { children: React.ReactNode }) {
const { data: sessions, isLoading } = useGetSessions();
const { slug } = useParams({ strict: false });
const router = useRouter();
const [activeSession, setActiveSession] = useState<Session | null>(null);

useEffect(() => {
// some logic to set state and url
}, []);



return (
<AuthContext.Provider
value={{
activeSession,
}}
>
{children}
</AuthContext.Provider>
);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const { data: sessions, isLoading } = useGetSessions();
const { slug } = useParams({ strict: false });
const router = useRouter();
const [activeSession, setActiveSession] = useState<Session | null>(null);

useEffect(() => {
// some logic to set state and url
}, []);



return (
<AuthContext.Provider
value={{
activeSession,
}}
>
{children}
</AuthContext.Provider>
);
The issue is that in AuthContext, the isLoading is true. Isn't the point of the beforeLoad in __root that isLoading isn't true? What am I missing?
eastern-cyan
eastern-cyan5mo ago
please provide a complete minimal example, e.g. as a git repo

Did you find this page helpful?