I am trying to make a simple to-do/reminder single-page application using react. I want to add components dynamically to the page whenever data is submitted through a form. I have a flask backend set-up. This is the function called when the form is submitted:
submitNewReminder(event){
event.preventDefault()
let form = document.getElementById('new-reminder-form')
const data = new FormData(form)
const plainFormData = Object.fromEntries(data.entries());
const JSONdata = JSON.stringify(plainFormData)
fetch('http://localhost:5000/addrem',{
method: 'POST',
headers:{'Content-Type': 'application/json'},
body: JSONdata,
}).then(resp => resp.json().then(data =>{
if (data){
this.response = data
}
}))
this.setState({refresh:(this.state.refresh?0:1)})
console.log(this.state.refresh)
}
The response from backend contains all the reminders extracted from the database.
The state refresh is used to 'reload' the content of the page with the updated reminders. I toggle it between 1 and 0 so that the state gets updated and can re-render the component with added data each time a reminder is added. The render method looks like this:render(){
if (!this.state.isLoggedin && (this.state.refresh === 1 || this.state.refresh === 1)){
return(
<div>
<LoginForm do={this.submitForm} toggleSignup={this.toggleSignup}/>
</div>
)
}
else{
return(
<div className='container text-center'>
<h1>Logged in!</h1>
<div className="row">
{ this.response.reminders.map((item,i=0) =>{
return <Card key={i++} reminder={item}/>
}
)}
<AddReminder addRem={this.toggleAddReminder} cancel={this.cancelAdd} submit={this.submitNewReminder}/>
</div>
</div>
)
}
}
With each reminder added, the a new <Card />
component is created which displays the data in it. This is the behaviour I want.
The Problem:
For the first submit of the form, no new cards/reminders are produced. But for the succeeding submits, a new card is displayed each time. I am unable to understand this behaviour. Theconsole.log(this.state.refresh)
shows that the first time it is submitted, the value of refresh
remains 1 (refresh is initialised with value 1). Is there something wrong in my code? Is this the right method to achieve what I want?