Skip to content

Instantly share code, notes, and snippets.

@davidhellmann
Forked from j2is/Craft Add Items To Cart
Created June 29, 2021 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhellmann/f314b692d8eadcbe79d9e28eec1f9605 to your computer and use it in GitHub Desktop.
Save davidhellmann/f314b692d8eadcbe79d9e28eec1f9605 to your computer and use it in GitHub Desktop.
How to add items to the cart, this example is headless but can be modified for a regular setup by also posting a CSRF token.
import axios from "axios";
async function request(request) {
if (!request) {
return { data: undefined, error: "no request" };
}
const data = typeof FormData !== "undefined" ? new FormData() : {};
if (request.data) {
Object.entries(request.data).forEach(([key, value]) => {
data.append(key, value);
});
}
return await axios({
url: request.url,
method: request.method || "post",
data,
headers: {
Accept: "application/json"
}
})
.then(d => {
return { data: d.data, error: undefined };
})
.catch(error => {
return { data: undefined, error };
});
}
const saveNewLineItems = async (cartNumber, newItems) => {
const method = "POST";
const payload = {
action: `commerce/cart/update-cart`
};
if (cartNumber !== undefined) {
payload.orderNumber = cartNumber;
}
// payload[window.Craft.csrfTokenName] = window.Craft.csrfTokenValue; // Append CSRF Token if not headless
if (Object.keys(newItems).length) {
Object.keys(newItems).map(function(key, index) {
const item = newItems[key];
payload[`purchasables[${index}][id]`] = item.purchasableId;
payload[`purchasables[${index}][qty]`] = item.quantity;
payload[`purchasables[${index}][options][Size]`] = item.size; // optional
});
}
const { data, error } = await request({
url: `${process.env.api}`,
method,
data: payload
});
if (!data || error || !data.cart) {
return Promise.reject();
}
if (data.success) {
return data.cart;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment