Created
June 29, 2021 09:10
-
-
Save j2is/58a1c46c524618808146ade43b31b1a9 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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