简体   繁体   中英

How to access API with Auth0 JWT in redux?

I'm using Auth0 to secure my API endpoints with JWT. The "useAuth0().getTokenSilently()" is a context hook and it throws the "error: Invalid hook call" because I'm calling it in a js file instead of in a React component; I'm not sure how to approach to this problem. Any suggestions would be much appreciated. :)

// Actions.js

export const fetchIssues = () => async (dispatch) => {

  try {
    const token = await useAuth0().getTokenSilently(); // this line is throwing the error.

    const response = await api.get("issues", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    const responseData = await response.json();

    dispatch({ type: FETCH_ISSUES, payload: responseData });
  } catch (error) {
    console.log(error);
  }
};

Hooks can only be called inside of the body of a function component. This hook requires a parent component that has a provider wrapped to provide the context of getTokenSilently().

So wherever you want to use useAuth0(), you have to make sure that component is a child of the Auth0Provider.

I currently use it by calling getTokenSilently, then I just set it to axios's header directly without redux for my APIs.

If you do have a way around writing this in a standalone method, do let me know because I am also interested in writing this in a separate method too.

To use Auth0 outside of React function component you can use the Auth0-js client lib to not being constrained by the React wrapper and be able to work outside of function component.

Potential downside is you'll have to implement behaviours that React wrapper previously handle for you. Tentation would be to keep working with the React wrapper in parallel of using your own Auth0 instance. This can lead to issues in states and configs if you are not rigorous in keeping synchronisation between them on each instance updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM