How to make a post request from array of object with Axios?

Viewed 486

My endpoint only accept only 1 object

Axios.post('www.url.com', { 
    giftAGift: false, 
    productId: "1030567", 
    quantity: 1, 
    storeId: 0, 
    variantId: ""
})

What I have is an array of object

let object = [{"giftAGift": false, "productId": "1234", "quantity": 1, "storeId": 0, "variantId": ""}
 {"giftAGift": false, "productId": "12345", "quantity": 1, "storeId": 0, "variantId": ""}
 {"giftAGift": false, "productId": "123456", "quantity": 1, "storeId": 0, "variantId": ""}
 {"giftAGift": false, "productId": "`123456", "quantity": 1, "storeId": 0, "variantId": ""}]

What is the best way to make a post request when I want to send all data when I press only 1 time.

2 Answers

Then you must loop through the array and make an API call for each.

let array = [{"giftAGift": false, "productId": "1234", "quantity": 1, "storeId": 0, "variantId": ""}
 {"giftAGift": false, "productId": "12345", "quantity": 1, "storeId": 0, "variantId": ""}
 {"giftAGift": false, "productId": "123456", "quantity": 1, "storeId": 0, "variantId": ""}
 {"giftAGift": false, "productId": "`123456", "quantity": 1, "storeId": 0, "variantId": ""}]


array.forEach((obj) => {
  Axios.post('www.url.com', obj);
})

Edit. Using Promise.allSettled

const promises = array.map((obj) => {
  return Axios.post('www.url.com', obj).then((response) => response.data);
});

Promise.allSettled(promises)
.then(() => ...)
.catch(() => ...)
.finally(() => ...)

Well its not good practice because you are inserting multiple records at a time. You should make multiple insert backend route for handling this. So after this in one API call you can insert e.g., 30 records instead of 30 multiple requests.

But if you still want to make multiple requests then you can done job using following code:

let array = [{"giftAGift": false, "productId": "1234", "quantity": 1, "storeId": 0, "variantId": ""},
 {"giftAGift": false, "productId": "12345", "quantity": 1, "storeId": 0, "variantId": ""},
 {"giftAGift": false, "productId": "123456", "quantity": 1, "storeId": 0, "variantId": ""},
 {"giftAGift": false, "productId": "`123456", "quantity": 1, "storeId": 0, "variantId": ""}]


let arr=arr2.map((obj)=>Axios.post('url.com', obj));

let promise=Promise.allSettled(arr).then((data)=>{
  console.log(data);
})

Related