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: https://gist.github.com/klequis/fd9c3cf5b025cc26a282ea30ef8ff6da