My task is to display flash message("successfully created") on clicking the submit button.[On clicking the submit button , data will be stored in the server]I have run this command npm i react-flash-message.
<form onSubmit={this.handleSubmit}>
<input type="submit" value="Submit" />
</form>
handleSubmit function:
handleSubmit(event) {
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description
})
}).then(res => {
return res.json()
})
.then(data => console.log(data))
.then(() => {
window.location.reload(false)
/* return (
<div>
<FlashMessage duration={5000}>
<strong>I will disapper in 5 seconds!</strong>
</FlashMessage>
</div>
) */
})
/* window.flash('record has been created successfully!', 'success') */
.catch(error => console.log('ERROR from create component'))
}
}
I have commented the code I have tried to display flash message. But it is not working. Please someone help me to display the flash message.
According to react-flash-message page , you should include the FlashMessage in your render. So you may need to have a flag variable to set as true when you want to show the FlashMessage
Example: in your render :
<form onSubmit={this.handleSubmit}>
<input type="submit" value="Submit" />
{ this.state.showMessage &&
<div>
<FlashMessage duration={5000}>
<strong>I will disappear in 5 seconds!</strong>
</FlashMessage>
</div>
}
</form>
handleSubmit function :
handleSubmit(event) {
this.setState({ showMessage: false });
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description
})
}).then(res => {
return res.json()
})
.then(data => console.log(data))
.then(() => {
this.setState({ showMessage: true });
})
/* window.flash('record has been created successfully!', 'success') */
.catch(error => console.log('ERROR from create component'))
}
}
main function if you are using class:
constructor(props) {
super(props);
this.state = {
showMessage: false
};
}
https://www.npmjs.com/package/react-flash-message
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With