I am working on capturing the cartID in a JavaScript variable from a JSON response.
Here is the code I have so far that requests the cart information:
function getCart(url) {
return fetch(url, {
method: "GET",
credentials: "same-origin"
})
.then(response => response.json())
};
var cartID = 'unknown';
getCart('/api/storefront/carts')
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));
The data logged in the console looks like this:
Extract of full data:
[{"id":"c5f24d63-cd9a-46f2-be41-6ad31fc38b51","customerId":1,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdd0d8fddavalue="">[email protected]</a>", ................. }]
I've attempted different methods to capture the cart ID into the variable cartID, but it always shows as 'unknown' and is logged before the data response.
Do you have any suggestions on how to delay until the response is ready and then assign 'cartID' with the id value?