I have a React.js project with a simple sign in function. After the user is authorized, I call history.push method which changes the link in the address bar but does not ren
Not Working on this one ->
handleSubmit(event) {
event.preventDefault();
this.setState({ isLoading: true })
const { username, password } = this.state;
this.props.onLoginRequest(username, password, this.props.history).then(result => {
console.log("Success. Token: "+result.token); //I do get "success" in console
this.props.history.push('/servers') //Changes address, does not render /servers component
});
}
const mapActionsToProps = {
onLoginRequest: authorization
}
Because in this handleSubmit
method you are calling this.props.history.push()
inside a promise so the this
is pointing to the Promise's instance not your current class instance.
Try this One ->
handleSubmit(event) {
event.preventDefault();
const { history: { push } } = this.props;
this.setState({ isLoading: true })
const { username, password } = this.state;
this.props.onLoginRequest(username, password, this.props.history).then(result => {
console.log("Success. Token: "+result.token); //I do get "success" in console
push('/servers') //Changes address, does not render /servers component
});
}
const mapActionsToProps = {
onLoginRequest: authorization
}
Now In this Statement ->
handleSubmit(event) {
event.preventDefault();
this.setState({ isLoading: true })
const { username, password } = this.state;
this.props.onLoginRequest(username, password, this.props.history).then(result => {
console.log("Success. Token: "+result.token);
//this.props.history.push('/servers')
});
this.props.history.push('/servers')
}
You are correctly calling this.props.history.push() since it is out of the promise and referring to the Current Class instance.