Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Creation for Multiple API Calls

Can an object be created with the help of which multiple API calls can be made? For example

  • I have two APIs to call, namely:-
export const getCropDetails = (cropDetails, token) => API.get(`/crop?name=${cropDetails}`, {
    headers: { "Content-Type": "application/json", "authorization": localStorage.getItem("token") }
});
export const getCropDetails = (cropDetails, token) => API.get(`/crop/details?name=${cropDetails}`, {
    headers: { "Content-Type": "application/json", "authorization": localStorage.getItem("token") }
});
  • Here I'm calling crops in the first and crop/details in the second.
  • I want to know if a class can be written, such that I can access them anywhere, rather than calling them multiple times every time.
like image 535
Akash Suklabaidya Avatar asked Feb 22 '26 06:02

Akash Suklabaidya


1 Answers

Are you looking for something like this ?

class MultipleAPI {
    constructor() {}
    async makeMultipleAPICalls() {
        const getCropDetailsOne = (cropDetails, token) =>
            API.get(`/crop?name=${cropDetails}`, {
                headers: {
                    "Content-Type": "application/json",
                    authorization: localStorage.getItem("token")
                }
            });
        const getCropDetailsTwo = (cropDetails, token) =>
            API.get(`/crop/details?name=${cropDetails}`, {
                headers: {
                    "Content-Type": "application/json",
                    authorization: localStorage.getItem("token")
                }
            });
        const results = await Promise.all([
            getCropDetailsOne,
            getCropDetailsTwo
        ]);
        return results;
    }
}

const h = new MultipleAPI();
console.log(h.makeMultipleAPICalls().then(res => console.log("res", res)));
like image 115
DanteDX Avatar answered Feb 23 '26 19:02

DanteDX