I want to show error (or success) message using FlashMessage
while having my page reload at desired time
I'm using FlashMessage
and my code looks like
render() {
return (
{this.state.error ? <FlashMessage duration={5000}><strong>{this.state.error.message}</strong></FlashMessage> : ''}
//Some table here presenting data
<Button variant="outline-info" type="submit" size="lg" block className="button-custom" onClick={this.handleSubmit.bind(this)}>
Submit
</Button>
)}
for my stateful component, the error
is loaded by
handleSubmit(event) {
let data = {
name: this.state.name,
unit_price: this.state.unit_price,
length: this.state.length,
time: this.state.selectedDate,
instructor: this.state.instructor,
}
ApiService.postLesson(data)
.then(res => {
this.setState({
message: 'Success!'
});
})
.catch(error => {
this.setState({
message: error,
error: error,
});
console.log(error);
})
};
and my ApiService.postLesson
is
const instance = axios.create({
headers: {
"Content-Type": "application/json",
Authorization: 'Token ' + localStorage.getItem('token')
},
});
export default {
postLesson: data =>
instance({
'method': 'POST',
'url': BACKEND_LESSONS_URL,
'data': data
}),
// some other services
Now my problem is every time I click Submit, whether it's successful or not, it reloads the page. Because of that, I think my state is reloaded and the error is gone. If I add event.preventDefault()
in handleSubmit
, then I can see the message but then my content in the table would not be updated. What's a solution for this?
it rerenders the component
orreload the page?
– Alrickevent.preventDefault()
the table won't update.Normaly when you retreive some data from the server.That means that you have some initial data that is getting rendered in your component that you retreived using thecomponentDifMount()
method
.So if you want to update your data, the logging of updating the state should be done by making some comparison with a previousstate
.Have you used the lifecycle method
that udated the state? – AlrickcomponentDidMount
indeed. I'm a little confused where/when the update should happen and how to compare the previous state in this case. The error is returned as an async call, so the state is set some time after. Should I useshouldComponentUpdate
and compare the previous state's error and current state's error? – DemiseFlashMessage
before(And this question was asked long ago so I thought maybe an alternative solution would be helpful) but I do know of an alternative so I do not know if you want me to share that solution? If yes the specify then I will give solution – Planography