Reputation: 484
I have three components; Parent, ChildA, Child B. The parent is defined like this:
class Parents extends Component {
getPersons = () => {
fetch('/Persons')
.then(persons => this.setState({ persons:persons })
}
updateTable = () =>
this.setState({ update: true })
}
Now, ChildA is a form where I can create new persons. ChildB is a table showing all the persons. I would like ChildB to re render when I have created a new person.
I tried to call an updateTable() function on childA immediately after getPerons(), like this:
class ChildA extends Component {
onSubmit() {
this.getPersons();
this.updateTable();
}
}
The issue is that the table is updated before persons are fetched. What is the correct way to handle this?
I guess could define the getPersons() in childA and then add ".then(this.updateTable())" but I am using the getPersons in initial rendering as well, so I don't want to move it away from Parent
Upvotes: 0
Views: 639
Reputation: 33153
You don't have to continue the promise chain all in the same place. The first function can return the promise and you can continue the chain wherever you want.
class Parents extends Component {
// remove the brackets to return the promise
getPersons = () => fetch('/Persons')
.then(persons => this.setState({ persons:persons })
updateTable = () =>
this.setState({ update: true })
}
class ChildA extends Component {
onSubmit() {
this.getPersons().then( this.updateTable );
}
}
Upvotes: 3