AasthaChaudhary
AasthaChaudhary

Reputation: 99

Multiple API calling in functional Component REACT JS

I am having a SEARCH button in my component and I want to call 2 different APIs when user clicks on this button.

<div className="ShipCard">
        <div className="grid2">
          <h1>Enter SO Gateway ID </h1>
          <input type="text" name="gatewayID" onChange={changeData}/>
        </div>
        <button className="ShipSearch" onClick={onSearch}>Search</button>
 </div>

Assume 2 different APIs are A and B. I want to call B after A. How can this be achieved ?

in main component

import {A,B} from './service';
const onSearch = () =>{
A().then(response)=>{}
B().then(response)=>{}
}

In Service component

const A =async() =>{
return await axios
  .get("https://xyz")
}

const B =async() =>{
return await axios
  .get("https://abc")
}
export {A,B};

Upvotes: 0

Views: 840

Answers (3)

taofeek
taofeek

Reputation: 81

You can combine both axios.get into one call. Such as

const onSearch =()=> {
return axios.all([
axios.get('https://xyz/'),
axios.get('https://abc/')
])
.then(axios.spread((a, b) => {
// do whatever you want with the responses or return a,b
return {a,b};
}));
}

Upvotes: 0

Meer Humza
Meer Humza

Reputation: 59

use can use the below async function. Once the first request resolve it will move to the next line due to async await.

const onSearch =  async () => {
    try {
      const responseA = await A();
      const responseB = await B();
    }catch(e){
      console.log(e,'error');
    }
  }

Upvotes: 0

cSharp
cSharp

Reputation: 3169

Use await.

const onSearch = async () =>{
  const responseA = await A()
  //do something with responseA
  const responseB = await B()
  //do something with responseB
}

Upvotes: 0

Related Questions