Reputation: 377
so what i'm trying to do is I want to change Route
after a function is done, for example i want user to enter his/her user name and password and if they were true redirect them to their profile, but i don't know how to do that and i don't want to do it using something like this
window.location.href = "http://localhost:3000/dashboard"
so for example here's my code and i want to redirect it to Dashboard after the api
call is done.
const handleSubmit = event => {
event.preventDefault();
const user = {
phone_number: this.state.phone_number,
password: this.state.password,
gcm_id: 1,
dev_type: "Web"
};
const headers = {
'Authorization': "abc",
'content-type': 'application/json'
}
localStorage.setItem('phone_number', this.state.phone_number);
axios.post(`sth`, user, {
headers: headers
})
.then(res => {
localStorage.setItem('api_key', res.data.api_key)
})
.catch(err => { console.log(err) })
}
In here i want it to change Route after the `api_key' is set.
Upvotes: 0
Views: 42
Reputation: 2948
Wrap your class component with the withRouter
HOC provided from react-router
.
import { withRouter } from "react-router";
Then on success add this
.then(res => {
localStorage.setItem('api_key', res.data.api_key);
this.props.history.push('dashboard');
})
if you are using a function component:
import { useHistory} from "react-router-dom";
const history = useHistory();
.then(res => {
localStorage.setItem('api_key', res.data.api_key);
history.push('dashboard');
})
Upvotes: 2
Reputation: 1685
You need to add this.props.history.push('/dashboard')
after the api key is set to route to the appropriate page.
Also add withRouter
to the class export like export default withRouter(Register)
Upvotes: 2