React history.push() not redirecting

Johan kleine Bjällskog
2 min readMar 31, 2021

That ended up being my second googling, my first googling was “react redirect after logout”.

My first googling made me find an answer and it looked promising and easy. I ended up with something like this(see below), and you probably have to. The History.push sounded like the easy savior to this problem and I was excited, but as you know it did not work. It only changed the url and did not redirect to the page.

import React, { } from 'react';
import axios from 'axios'
import { useHistory } from "react-router-dom";
const Header = () => {
let history = useHistory()
const handleLogout = (event) => {
event.preventDefault();

axios
.get(`/logout`)
.then(res => {
history.push("/login");
})
.catch(err => {
console.log(err)
})
};
return (
<>
stuff
</>
);
};
export default Header;

So as the headline says, I started to google for the solution, why did it not work and what could I do to make it work, well I found a lot of answers one more complicated than the other and not so many was good for my solution.

I started to console.log some of my own and tried some stuff and well I came up with the most simple and easy fix. I changed

history.push("/login");

to

history.go("/login");

and it worked perfect, I got redirected to the login page after logged out.

I hope I saved some people some hours, this was not meant to be the longest of articles ;) enjoy. Hope it solved your problem to.

--

--

Johan kleine Bjällskog

Lead front-end developer, movie lover and a junkie of series.