How can I check for authentication errors on every loader call without copy and paste boilerplate?
I have a gist written here: https://gist.github.com/jeffreytgilbert/c65f14dd107e840ee893af2ed6ebeeae
It both handles the async await and checks for the auth error code(see: useGetApi), but it wont import correctly for use in loaders. When trying, I receive the error: "SyntaxError: Importing binding name 'useGetApi' is not found." The Route/Loader code is as simple as this:
const eventArtistsSearchRoute = createRoute({
/* irrelevant component and param parsing code here */
loader: ({ params: { eventId } }) => {
return useGetApi(apiBasePath+'/api?event_id='+eventId);
},
});
Can you use hooks in the loader? If not, how can I update the login context with loader? Can you not update any state with loader? How can I do this? I don't want to copy and paste an auth check for every single page on the site. That's bananas.
4 Replies
harsh-harlequinOP•2y ago
Trying to understand if switching to the router context would be a good idea for authentication checks, however it looks like you can only augment the context beforeLoad based on what the docs say, so that's not going to work since I need to set the context after checking the response from the API in the loader.
exotic-emerald•2y ago
Can you use hooks in the loader?
noexotic-emerald•2y ago
did you have a look at https://tanstack.com/router/v1/docs/framework/react/examples/authenticated-routes-context ?
React TanStack Router Authenticated Routes Context Example | TanSta...
An example showing how to implement Authenticated Routes Context in React using TanStack Router.
fair-rose•2y ago
Its also called out here in the docs, if you missed it.
https://tanstack.com/router/v1/docs/framework/react/guide/authenticated-routes#authentication-using-react-contexthooks