Reputation: 36391
I want to make a loading indicator on user login, but for some reason the JSX conditional element does not update:
class LoginPage extends Component {
constructor (props) {
super(props)
this.state = {
waitingOnLogin: false,
...
}
this.handleLogin = this.handleLogin.bind(this)
}
handleLogin (event) {
event.preventDefault()
this.state.waitingOnLogin = true
this.props.userActions.login(this.state.email, this.state.password)
}
render() {
return (
<div className='up'>
<form onSubmit={e => this.handleLogin(e)}> ... </form>
{this.state.waitingOnLogin && <Spinner message='Logging you in'/>} // This does not appear
</div>
)
}
}
Why does the waitingOnLogin
is being ignored by the JSX?
Upvotes: 0
Views: 56
Reputation: 281696
Don't mutate state directly use setState
. setState calls for rerender and hence after that your change will reflect but with direct assignment no rerender
occurs and thus no change is reflected. Also you should always use setState
to change state
handleLogin (event) {
event.preventDefault()
this.setState({waitingOnLogin:true});
this.props.userActions.login(this.state.email, this.state.password)
}
Upvotes: 1
Reputation: 104379
Always use setState
to update the state
value, never mutate the state
values directly, Use this:
handleLogin (event) {
event.preventDefault()
this.setState({ waitingOnLogin: true });
this.props.userActions.login(this.state.email, this.state.password)
}
As per DOC:
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
Check the details about setState.
Upvotes: 1