'How to update data at the same time after an ajax post request
I am doing a ajax post request to
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(samepleData)
})
.then(response => {
return response.json();
})
and after the product has been added to the cart, I open a drawer to show all items in the cart using a GET request to the endpoint
fetch(window.Shopify.routes.root + 'cart.js')
.then(response => response.json())
.then((cartData) => {
console.log(cartData);
if(cartData) {
showCartDrawer(quick_shop_desktop_container, cartData);
}
}).catch((err) => {
console.log(err);
})
and everything is working, it is loading and fetching data, but now once I am in the cart drawer, I have an option to increase quantity and decrease quantity, so everytime someone clicks on increase quanity, it should again make a post request to the first endpoint, and the product will be updated, but the new info will not gonna be shown at the same moment, How to update all the data after the product quantity is increased without refreshing the page and at the same moment? I haven't woked with this type of conditions before, any guide please?
EXAMPLE CODE:-
let samepleData = {
'items': [{
'id': myid,
'quantity': quantityValue
}]
};
btn.addEventListener('click', () => {
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(samepleData)
})
.then(response => {
return response.json();
}).then((data) => {
console.log(data);
if (data) {
fetch(window.Shopify.routes.root + 'cart.js')
.then(response => response.json())
.then((cartData) => {
console.log(cartData);
if(cartData) {
showCartDrawer(quick_shop_desktop_container, cartData);
}
}).catch((err) => {
console.log(err);
})
}
).catch((err) => {
console.log(err);
})
}
else {
addToCartBtn.innerHTML = `<span>Fail</span>`
}
})
})
And now inside the showCartDrawer
test.innerHTML = cartData.items.map(cartItem =>
`<div class="selliy-cart-item">
<h2>${cartItem.price}</h2>
</div>`
).join('');
increasequantityfromdrawer.addEventListener('click', () => {
let newdata = {
'items': [{
'id': myid,
'quantity': newvalue
}]
};
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newdata )
})
.then(response => {
return response.json();
})
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
