Using @auth0/auth0-spa-js outside of a React Component

I using auth0-spa-js with the SPA sample React: Login as reference. The sample implements Auth0 functionlity using React hooks which is very usful when using the functionality from a React component. I did run into a problem:

However, it makes API calls directly from a React component. If you need to do API calls from outside of a React component, as I do, you can’t becuase hooks can only be used by React components.

My app is a very typical React + Redux + redux-thunk app. An API call is initiated in a React component by calling an action which is a thunk. The action uses a function from another module (conveniently named api.js) which is not a React component. api.js needs the access token so I would want to call getTokenSilently from it, however this is not possible because hooks cannot be used outside of a React component.

My solution to this was to modify the sample/tutorial code in react-auth0spa.js by moving auth0Client & getTokenSilently outside of the Auth0Provider and to export getTokenSilently.

I’m wondering if this approach is sound and if there is a better approach.

I made a gist of the modified code: Modification to Auth0Provider in react-auth0-spa.js · GitHub


Thanks for this @klequis. We’re looking at pulling the React wrapper out from the sample and moving it into a library in its own right, so this is great feedback for us.

There’s obviously a use-case here for being able to access the client outside of the wrapper. I’ve left a comment on the Gist; let’s iterate on it and see where we get to.

replied in the gist.

I updated the gist with the solution that is working well for me.

Thanks a lot @klequis for sharing it with the rest of community!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.