简体   繁体   中英

making second api call after getting data from the first api

I have this first API call which gets me some data and once I have got the data from this api , only then I need to make the second api call . It must happen in the series and not parallelly. How can we do this in react ComponentDidMount? I am listening to firebase . Let us suppose that the first api gets me a matchId and now we need to use this matchid to make second call just after first api call without any click .

Let us suppose that this is my first firebase call .

const cardsListener = 
        getDATA()
        .onSnapshot( (doc)=>{
            console.log("doc is ",doc);
            let data = doc.data();
            console.log("data",data);
            this.setState({
                 datainstate:data
            });
        });

Thanks to async/await , you can wait until an action is done.

componentDidMount() {
  this.firstApiCall()    
}

async firstApiCall() {
  await fetch("http://myurl.com", {
     method: 'POST',
     body: JSON.stringify(data), // data can be `string` or {object}!
     headers:{
       'Content-Type': 'application/json'
     }
   })
   .then(res => res.json())
   .then((responseJson) => {
     //if it worked
     this.secondApiCall()
   })
   .catch(error => console.error('Error:', error))
}

secondApiCall() {

}

There are many ways you could do this. My preferred way is to use async await. I'll give an example of how you would use this below.

        const getData = async() => {
          try {
            const apiCall1 = await axios.get(SOME_URL);
            const apiCall2 = await axios.get(SOME_URL/apiCall1.data.id)
            return apiCall2
          } catch(e) {
            return e
          }
        }

It's a silly example but you hopefully get the point. I make my first API call and await the response. Then I make my second API call using some data from the first call then return. You can do whatever logic you want in-between that.

You could also use a callback or promise but I think async await is clearer, and generally less code.

Async Await Documentation - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function Promises Documentation - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise Callback Documentation - https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

You can follow something like this:

componentDidMount() {
  fetch("apiUrl").then(res => {
    //Do whatever you want to do with the response or get the id
    const {id} = res;
    fetch(`apiUrl/${id}`).then(response => {
      // Do anything with the response of the api call here
    }).catch(error => {
      //Thing to do on error
    });
  }).catch(err => {
    //Thing to do on error of 1st api call
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM