'How to make a post request from array of object with Axios?
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.
Solution 1:[1]
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);
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asad Haroon |
