Im using a redux connected component in react. Just having trouble rendering a button after the handleSubmit onClick handler is called. It only appears after I refresh the page, which may indicate an async issue. So in this component, I have a redux state property called status and have mapped it to the props of my local state. I have heard that when the state or props change, that is when the component rerenders. So what I thought about doing is in my render method, if this.state.showButton is true, then this button would show. However it doesnt. I also console logged this.state.showButton and it is indeed true.
But button is not there. I did the following:
class VerificationForm extends React.Component {
constructor(props) {
super(props);
this.state = {
formError: false,
showModal: false,
showButton: false
};
}
handleSubmit = (e) => {
e.preventDefault();
this.setState({
formError: showFormError
});
verifyLevelOne()
.then((data) => {
const { status } = this.props;
const verified = status === 'VERIFIED';
this.setState({
showButton: verified
}, () => {
actions.showSubmissionNotification(data);
});
console.log('Hereeeeee', this.state.showButton);
});
}
render() {
const {
classes, actions, status
} = this.props;
const {
formError, showModal
} = this.state;
return (
<div>
<form onSubmit={this.handleSubmit} autoComplete="off">
<Grid className={classes.container} container direction="column" alignItems="center" xs={12}>
<Grid container direction="column" xs={11}>
<span style={{ display: 'flex', justifyContent: 'space-around' }}>
<Button fullWidth onClick={this.handleSubmit} type="submit" variant="contained" color="primary">Submit Information</Button>
{ this.state.showButton && <Button onClick={this.handleShowModal} variant="contained" color="primary">Proceed</Button> }
</span>
</Grid>
</Grid>
</form>
</div>
);
}
}
function mapStateToProps(state) {
return {
status: state.global.verification.status,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: {
...bindActionCreators({
showNotification,
showSubmissionNotification,
}, dispatch)
}
};
}
const base = withRouter((withStyles(styles)(VerificationForm)));
export default connect(mapStateToProps, mapDispatchToProps)(base);
setState is executed asynchronous, so if you console.log just after the setstate it will not give you the right value
I would suggest to console.log in return of render just when you are using the state for sack of debugging.
refer below:
<span style={{ display: 'flex', justifyContent: 'space-around' }}>
<Button fullWidth onClick={this.handleSubmit} type="submit" variant="contained" color="primary">Submit Information</Button>
{ console.log(this.state.showButton)}
{ this.state.showButton && <Button onClick={this.handleShowModal} variant="contained" color="primary">Proceed</Button> }
</span>