Iggy
Iggy

Reputation: 5251

Wait for fetch request to finish before running the next method in React?

I am running Rails on backend and React on frontend. I have created a function that utilizes fetch method so React can talk to Rails - this function sends a POST request to Rails.

Ideally, I would like the following:

(1. GET all scores from rails API) -> (2. save them as states) -> (3. From React, perform POST/ PUT/ DELETE to Rails) -> (4. GET all updated scores from rails API) -> (5. save them as states) -> (&c.)

Ideally, I would like step (3) to completely finish before (4) executes, that way if I POST a new score on React to Rails, step 4 would fetch and GET the new score and my states will be up-to-date.

My problem is, sometimes step (4) would happen before step (3) even finishes. I said sometimes because sometimes it would update the states when I created/ deleted new score, and sometimes it would not update the states when I created/ deleted a new score.

Currently my function looks like this:

handleDelete(){
  ...
  Client.deleteScores(maxWeek).then(this.getStudentsAndScores());
}

#deleteScores:
function deleteScores(week){
  return fetch(`delete_latest_week`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      week: week
    })
  });
}

#scores_controller (rails):
def delete_by_week
  Score.destroy_all(:week => params[:week])
  head :no_content
end

It says delete while it shows method POST. Long story short, it is deleting posts via POST method. Detail here. The gist of it is, I have a fetch POST method that need to be finished before React does something else.

The then function, getStudentsAndScores() is the function that fetches GET data from Rails. I want it to wait for Client.deleteScores() to finish first before GETting the data, but it seems like getStudentsAndScores ran before it finished with deleteScores(). In short, after I deleted it, when it does not work, I have to refresh the page to see that it has been deleted.

How can I tell React to wait until it finishes with first request before executing the next function?

Upvotes: 0

Views: 2413

Answers (1)

Akhil
Akhil

Reputation: 629

The fetch call returns a promise. So, inside then you should not immediately call another function but rather provide a function which should be called when the promise resolves successfully. Try something like this -

handleDelete(){
  ...
  Client.deleteScores(maxWeek).then(this.getStudentsAndScores);
}

Upvotes: 1

Related Questions