I am working on react app. I have login component and others

Viewed 38

In the app component I have this code:

  const authAxios = axios.create({
    baseURL: 'http://127.0.0.1:8000',
    headers: {
      Authorization: `Bearer ${sessionStorage.getItem('token')}`
    }
  });

and I provide authAxios as context for all of my app component. Like the code below:

   <authtoken.Provider value={authAxios}>
    <Router>
      <Routes>
        <Route path='/' element={<Login />} />
        <Route path='/Home' element={<Home />} />
       
      </Routes>
    </Router>
    </authtoken.Provider>

The problem is when I login the app and fetch any request with authAxios it does not work and return 401. But when I refresh the page It work successfully. I think I know the reason (the App component after log in does not access the token in the sessionStorage ) but I do not know how to fix it. Sorry for taking long

1 Answers

first time you recive token from login API insert it into local storage like before but save it to redux or state or any variable that you have access from interceptor to pass token by variable instead of write and read from local storage at first time. because when you save token in local storage before refresh the component that want fetch token from local storage.

Related