T
TanStack2y ago
harsh-harlequin

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.
Gist
The wrong way?
The wrong way? GitHub Gist: instantly share code, notes, and snippets.
4 Replies
harsh-harlequin
harsh-harlequinOP2y 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
exotic-emerald2y ago
Can you use hooks in the loader? no
exotic-emerald
exotic-emerald2y ago
React TanStack Router Authenticated Routes Context Example | TanSta...
An example showing how to implement Authenticated Routes Context in React using TanStack Router.

Did you find this page helpful?