skip to Main Content

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};

3

Answers


  1. Use await.

    const onSearch = async () =>{
      const responseA = await A()
      //do something with responseA
      const responseB = await B()
      //do something with responseB
    }
    
    Login or Signup to reply.
  2. 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');
        }
      }
    Login or Signup to reply.
  3. 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};
    }));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search