Home > OS >  Axios Header not updated. User needs to manually reload page in React
Axios Header not updated. User needs to manually reload page in React

Time:06-19

I am trying to redirect to the home page after a login, but before I want to update the JWT token in the header.

login.tsx

...
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
  event.preventDefault();
  const data = new FormData(event.currentTarget);

  axiosInstance
      .post('token/', {
          username: data.get('username'),
          password: data.get('password'),
      })
      .then((res) => {
          localStorage.setItem('access_token', res.data.access)
          localStorage.setItem('refresh_token', res.data.refresh)
          axiosInstance.defaults.headers.common['Authorization'] = 'JWT '   localStorage.getItem('access_token')
          navigate('/', { replace: true })
      })
}
...

In the home page, as soon as it enters, it does a POST request (using the header set in Axios)

home.tsx

...
const updateData = () => {
  return axiosInstance.post(`words/update/`, {
    'timezone': Intl.DateTimeFormat().resolvedOptions().timeZone
  })
}

useEffect(() => {
  updateData()
}, [])
...

The problem here is that the POST request sends the header with the old JTW token (not the updated one). Only after refreshing the page, that it does use the updated header.

BTW, maybe this piece of information is relevant. This is how my App.tsx looks like:

App.tsx

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import AddWord from "./components/addWord";
import './App.css';
import Home from "./components/home";
import SignIn from "./components/signIn";
import SignUp from "./components/signUp";

function App() {
  return (
    <div className="container">
      <Router>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/add_word" element={<AddWord />} />
          <Route path="/login" element={<SignIn />} />
          <Route path="/register" element={<SignUp />} />
        </Routes>
      </Router>
    </div>
  );
}

export default App;

CodePudding user response:

I suggest that you can use Redux to store your token on the login page as soon navigate to the home page get the token from the redux state and apply it to the method.

CodePudding user response:

Finally worked! Here's my solution:

navigate('/', { replace: true })
window.location.reload()

Write "window.location.reload()" after navigate

  • Related