Hey folks, I’m using the use-snipcart package in Next.js and having trouble understanding how best to interact with the data.
My objective is to pull the product IDs from the cart into an array that I can pass down to each product as props, and use to determine if an item has already been added to the cart.
Once installed and imported, the following gets the current cart data. When I add this and check the console, I can see an object containing all of the data I’m looking for:
const { cart = {} } = useSnipcart();
console.log('cart', cart) // returns the current cart data
Good stuff. However, if I add another log trying to access specific data (for example, the cart count) it doesn’t work and throws an error when the app loads:
const { cart = {} } = useSnipcart();
console.log('cart', cart) // returns the current cart data
console.log(cart.items.count) //Expected to return "3", but throws error, nothing returned
But it DOES work if I add the same log after the app has rendered. So I think I don’t fully understand the syntax used in the first line.
Back to the objective: When the ‘cart’ object above returns I can see the data I’m looking for. Each product ID can be found at:
cart.items.items[0].id
cart.items.items[1].id
cart.items.items[2].id
etc…
How do I get those values to store in an array after the ‘cart’ object has been created/returned?