When the user clicks a button, I want the app to
- read text from an input field
- post it to MySQL to add as a new row
- pull all rows from MySQL (including the new row)
- update the react component state with the new data it just pulled
- and rerender a list of all that data for the user
The problem I'm seeing is that pulling down all rows doesn't include the one that was just posted unless I include a manual delay (via setTimeout).
This is what my 2 functions look like
// gets all data, updates state, thus triggering react to rerender
listWords() {
setTimeout(() => fetch("http://localhost:9000/listWords")
.then(res => res.text())
.then(res => this.setState({ wordList: JSON.parse(res)})), 2000)
}
// sends new word to the MySQL database, then kicks off the listWords process to refetch all data
addWord() {
fetch("http://localhost:9000/addWord", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
word: this.state.newWord
})
})
.then(res => res.json())
.then(this.listWords())
}
I shouldn't have to have that setTimeout in there, but when I remove it, the listWords update doesn't have the newly posted row.
My best guess is that either
- I'm messing up the promise
.then()
paradigm, or - MySQL responds to my POST request but doesn't actually add the row until the GET has already completed, thereby missing out on the new row.
How can I ensure the POST has successfully completed before I pull the rows again?
I am using react, express, sequelize, and for the DB it's MySQL in a docker container.