Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
Axios Header not updated. User needs to manually reload page in React

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;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

Finally worked! Here's my solution:

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

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda