Retrieving cart details

The getCart helper method in cart-helper.js retrieves and returns the cart details from localStorage.

mern-marketplace/client/cart/cart-helper.js:

getCart() {    if (typeof window !== "undefined") {      if (localStorage.getItem('cart')) {        return JSON.parse(localStorage.getItem('cart'))      }    }    return []}

In the CartItems component, we will retrieve the cart items using the getCart helper method in componentDidMount and set it to state.

mern-marketplace/client/cart/CartItems.js:

componentDidMount = () => {    this.setState({cartItems: cart.getCart()})}

Then the cartItems array retrieved from localStorage is iterated over using the map function to render the details of each item.

mern-marketplace/client/cart/CartItems.js:

<span key={i}> ...

Get Full-Stack React Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.