Using 'use-snipcart' to fetch cart data

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?

After some copy/pasting from a few other sources I managed to find something that works, although may not be the best solution and results in some unnecessary re-renders:

  const { cart = {} } = useSnipcart(); // Creates the cart object

  const [cartIds, setCartIds] = useState([]); // Empty array to be replaced with the cart IDs later

  // Using the 'useEffect' hook to only run when the cart object updates
  useEffect(() => {
    // Conditional to only run if the 'cart' object isn't empty
    if (JSON.stringify(cart) !== '{}') {
      var cartItemIds = [] // temporary array for the cart IDs
      cart.items.items.forEach(item => {
          cartItemIds.push(item.id); //looping through each ID and adding the value to the temporary array
        })
      setCartIds(cartItemIds) // replacing the original array with the fresh IDs
    }
  }, [cart]);

Would love to know if there’s a better way to do this