Currently, I am focused on developing a Shopify website and fine-tuning the functionality of the shopping cart. My onClick event triggers a function that initiates the process of adding items to the cart. The first step involves checking if there is an existing cartId stored in local storage. If not, a new cart is generated through a call which successfully returns with a newly generated id. This id is then stored in local storage and assigned to a local variable as the cartId by retrieving it using localStorage.getItem('cartId'). Subsequently, the addItemToCart function is invoked. However, upon inspecting the console.log output within that function, only the itemId and quantity values are passed correctly while the expected cartId appears as undefined. Despite confirming the accuracy of the locally stored variable multiple times, the correct value fails to be passed through.
This function is triggered from the onClick() event
async function addToCart(itemId, quantity) {
console.trace();
// Verify if a cartId was provided, if not make a request to create a new cart before adding the item
if (localStorage.getItem('cartId') === null) {
console.log('------------------------------')
console.log('Creating new cart with item...')
console.log('------------------------------')
const shopifyResponse = await createCart();
localStorage.setItem('checkoutUrl', shopifyResponse.checkoutUrl)
localStorage.setItem('cartId', shopifyResponse.cartId)
}
let savedCartId = localStorage.getItem('cartId')
console.log('--------------------------------')
console.log(`Adding items to existing cart: ID: ${savedCartId} ...`)
console.log('--------------------------------')
const shopifyResponse = await addItemToCart({
itemId,
savedCartId,
quantity
})
console.log(shopifyResponse)
}
The addItemToCart function intended to receive the cartId
import { postToShopify } from "./shopify";
export const addItemToCart = async ({ itemId, cartId, quantity }) => {
console.log(`Item Id: ${itemId}`)
console.log(`Cart Id: ${cartId}`) //Returns undefined no matter where I have the argument in the function
console.log(`Quantity: ${quantity}`)
try {
const shopifyResponse = await postToShopify({
query: `
mutation addItemToCart($cartId: ID!, $lines: [CartLineInput!]!) {
cartLinesAdd(cartId: $cartId, lines: $lines) {
cart {
id
lines(first: 10) {
edges {
node {
id
quantity
merchandise {
... on ProductVariant {
id
title
priceV2 {
amount
currencyCode
}
product {
title
handle
}
}
}
}
}
}
estimatedCost {
totalAmount {
amount
currencyCode
}
subtotalAmount {
amount
currencyCode
}
totalTaxAmount {
amount
currencyCode
}
totalDutyAmount {
amount
currencyCode
}
}
}
}
}
`,
variables: {
cartId,
lines: [
{
merchandiseId: itemId,
quantity,
},
],
},
});
return shopifyResponse;
} catch (error) {
console.log(error);
}
};