Skip to content
Advertisement

Use state token inside axios instance

I have a state with a token that i get from my api :

JavaScript

And I want to reuse the token in an Axios instance :

JavaScript

The problem is that I can not read the token via useSelector as :

JavaScript

I get the error message :

invalid hook call. hooks can only be called inside of the body of a function component

Any suggestion ? Thanks in advance

Advertisement

Answer

You can’t use hooks outside of function components or other hooks. However, you can create the axios instance without the token, and then update the instance (api) when you have it (see axios’s Config Defaults).

Note: you’ll need to prevent your app from using the axios instance before the token is set.

Define the api without the authorization header:

JavaScript

In one of your top components get the token, and apply it to the axios instance defaults:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement