0

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

2
  • What is this.getTeachers();? Commented Jan 6, 2019 at 10:49
  • @DarrenSweeney - Sorry, edited now to this.getPersons(); - My mistake Commented Jan 6, 2019 at 10:49

1 Answer 1

3

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 );
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for answering. I did what you propsed in ChildA and getting a "Cannot read property then of undefined" error? Not quite sure why - Any ideas?
@Alex5207 You need to also change the getPersons function to return fetch.
@Baruch - Yeah that seems to what I am doing wrong. Not quite sure how to do it, though. How can I return the fetch and still set state in the function?
@Alex5207 Please, re-read JJJ's answer carefully. The answer is literally in the second line of the example code.
I see - Wasn't aware that you could omit the return statement. It works now, amazing - Thank you both

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.