Reputation: 160
I'm trying to make my page redirect after login by using .then
type ajax. Everything's working except the history.push()
command:
axios
.post('http://localhost:8080/login', {
email,
password
})
.then((res) => {
sessionStorage.token = res.data.token;
const { sub } = JSON.parse(atob(res.data.token.split('.')[1]));
sessionStorage.email = sub;
})
.then(() => history.push("/reservations"))
.catch(() => setError(connectionError))
}
Instead of redirecting, it's logging in correctly but not changing the page. The page updates when I refresh, but still no redirect. Not sure if it matters, but here's my routing:
<Route path="/reservations" exact component={Reservations}/>
Help much appreciated
Upvotes: 0
Views: 1232
Reputation: 46
Try it this way:
axios
.post('http://localhost:8080/login', {
email,
password
})
.then((res) => {
sessionStorage.token = res.data.token;
const { sub } = JSON.parse(atob(res.data.token.split('.')[1]));
sessionStorage.email = sub;
history.push("/reservations");
})
.catch(() => setError(connectionError))
}
Upvotes: 0
Reputation: 911
Change .then(history.push("/reservations"))
to .then(() => history.push("/reservations"))
.
Upvotes: -1
Reputation: 741
I will add the answer from SiddAjmera, if history still doesn't work, you have to add a package history
npm install history
index.js
import React from "react";
import ReactDOM from "react-dom";
import { Router } from "react-router";
import { createBrowserHistory } from "history";
export const history = createBrowserHistory();
ReactDOM.render(
<Router history={history}>
<App />
</Router>,
node
);
import {history} from "./index"
axios
.post('http://localhost:8080/login', {
email,
password
})
.then((res) => {
sessionStorage.token = res.data.token;
const { sub } = JSON.parse(atob(res.data.token.split('.')[1]));
sessionStorage.email = sub;
})
.then(() => history.push("/reservations"))
.catch(() => setError(connectionError))
}
Upvotes: 1
Reputation: 39432
There's something wrong with the syntax of the last .then
. Shouldn't it be a callback method inside which you'll call history.push
?
Something like this:
axios
.post('http://localhost:8080/login', {
email,
password
})
.then((res) => {
sessionStorage.token = res.data.token;
const { sub } = JSON.parse(atob(res.data.token.split('.')[1]));
sessionStorage.email = sub;
})
.then(() => history.push("/reservations"))
.catch(() => setError(connectionError))
}
Upvotes: 2