-1

So, I have dependent data that I need to fetch from the REST API. The data A have some key information in data B, so it is necessary to make sure to fetch (and LOAD) data B before data A.

What is the best way of doing this in React?? I solved this problem with recursive function that accepts array of strings as API endpoints, and fire it one after another, but I wonder is this the proper way of sequential API call in React?

vl4d1m1r
  • 31
  • 1
  • 3
  • Check if this helps you https://stackoverflow.com/questions/61491795/dependent-api-call-in-react-functional-component – Harmandeep Singh Kalsi Aug 30 '20 at 18:32
  • Thanks @HarmandeepSinghKalsi. Solution in the link you sent is functional, and it IS the answer to my question, however, for my project, the recursive function that I already have is more reusable, I think. – vl4d1m1r Aug 30 '20 at 19:15

1 Answers1

1

If Fetch(A) is going to be dependent on Fetch(B), then you can simply leverage async-await to do this sequentially.

async () => {
  const res = await fetch(URL_FOR_B); // get data B first
  const data = await res.json();

  const nextRes = await fetch(URL_FOR_A, { param: data.params });
  const nextData = await nextRes.json();

  console.log("Data at the end: ", nextData);
};

There are other approaches too: then with wrapped Promise but await is clean and sequentially readable.

Abhilash
  • 2,026
  • 17
  • 21
  • This is a VERY good answer. Thank you very much! – vl4d1m1r Aug 30 '20 at 18:37
  • I think, however, that my original solution with recursive function is more reusable. I can use it for any number of cases where I should send a sequence of N functions to be executed in order. – vl4d1m1r Aug 30 '20 at 19:17