Skip to content
Advertisement

Use state token inside axios instance

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

const initialState = {
  isAuth: false,
  token: "",
};

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

const api = axios.create({
  baseURL: `${baseUrl}`,
  headers: {
    Authorization: `Bearer ${token}`,
  },
});

export default api;

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

const token = useSelector((state) => state.auth.token);

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:

const api = axios.create({
  baseURL: `${baseUrl}`,
});

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

const App = () => {
  const token = useSelector((state) => state.auth.token);

  useEffect(() => {
    if(token) {
      api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    }
  }, [token]);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement