T
TanStack•13mo ago
foreign-sapphire

How to avoid "loading" state when using beforeLoad

I'm using TanStack Router and Query in my React project, and I'm trying to conditionally handle the beforeLoad event based on the presence of a token in local storage. When I even have empty beforeLoad the pending state is appearing even for second. Here's what I'm trying to achieve: No Token: If there is no token in local storage, I want to skip the beforeLoad entirely to avoid showing a pending component. With Token: If a token exists, I want to trigger a request to my API to fetch user data during the beforeLoad event. I did sth like this and it seems to work but I don't know if it's correct and good practice 😄
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
token: AuthState['token'];
user: AuthState['user'];
}>()({
beforeLoad: !useStore.getState().auth.token
? undefined
: async ({ context: { queryClient, token, user } }) => {
// do sth here
},
component: GlobalLayout,
});
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
token: AuthState['token'];
user: AuthState['user'];
}>()({
beforeLoad: !useStore.getState().auth.token
? undefined
: async ({ context: { queryClient, token, user } }) => {
// do sth here
},
component: GlobalLayout,
});
I had before that check inside beforeLoad but if i was refreshing the page the pending component was showed for 1s even no request/promises where going
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?