React Flash Message: How to make the message show without refreshing the page but refresh on 200
Seems like you are on the right track and event.preventDefault()
is really necessary for what you are trying to achieve.
So, you can refresh the page on success by calling location.reload()
:
handleSubmit(event) {
event.preventDefault();
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!'
});
location.reload(); // refreshes the page
})
.catch(error => {
this.setState({
message: error,
error: error,
});
console.log(error);
})
}
It's not clear why do you need to refresh the entire page and bootstrap react app after successful postLesson()
calls. However, there are potentially better options for your case:
- re-fetching the list of items displayed in table view
- or adding new lesson to the list on 200 response
handleSubmit(event) {
event.preventDefault();
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!'
});
// 1. re-fetching list of items
// ApiService.getLessons().then((lessons) => {this.setState({lessons})})
// or 2. add newly posted lesson to the list
// this.setState({lessons: this.state.lessons.concat(data)})
})
.catch(error => {
this.setState({
message: error,
error: error,
});
console.log(error);
})
}
I hope this gives you a few ideas.