Search code examples
reactjsreduxaxiosuse-effect

axios request token returns null when refreshing page


"axios": "^0.20.0",
"react": "^16.14.0",
"redux": "^4.0.5",
"redux-logger": "^3.0.6",
"redux-persist": "^6.0.0",
"redux-thunk": "^2.3.0"

i am using axios and i'm sending a request in useeffect and it works but when i refresh the page (F5) the token that i fetch from redux and add it into axios instance is null

axios.interceptors.request.use(
  function (config) {
    const token = store.getState().auth.token;
    config.headers.Authorization = `Bearer ${token}`;
    // Do something before request is sent
    console.log("req config", config);
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

this is just a api call and in refresh my token is 'Bearer null' :

  useEffect(() => {
    getAssessments();
    getGroups();
    getAssessmentUsers();
  }, []);

Solution

  • You need to wait for the token to be rehydrated in you redux store after the refresh, it doesn't happen immediately. If this still doesn't work you need to verify that the token is persisted with redux-persist.

    useEffect(() => {
      if (token) {
        getAssessments();
        getGroups();
        getAssessmentUsers();
      }
    }, [token]);
    

    This useEffect hook will be triggered when the token has changed, eg: prevToken !== token, so you also need to add the if-statement to perform the requests when the token is not null