I am making an e-commerce website & I have no idea why I am getting this type error. I am trying to retrieve items from the cart that I stored in the local Storage but the items are coming back null. I’ve built this app multiple times for practice & I never had this problem in the past so I’m a little confused.
CartScreen.js
import {getCartItems} from "../localStorage";
const CartScreen = {
render: async () => {
const cartItems = getCartItems();
return `
${
cartItems.countInStock === 0
? `<div>Nothing is here <a href="/#/">Go Shopping</a></div>`
: cartItems.map((item) => `
<li>
<div class="cart-image">
<img src="${item.image}"/>
</div>
<div class="cart-name">
<div>
<a href="#/product/${item.product}">
${item.name}
</a>
</div>
<div>
<select class="qty-select" id="${item.product}">
<option value="1">1</option>
</select>
<button class="fw primary" id="${item.product}">
Delete
</button>
</div>
</div>
<div class="cart-price">
${item.price}
</div>
</li>
`).join('n')
}
`
}
}
I know the problem is coming from the cartItems variable but when I console.log() it I get this:
As you can see it says there are 5 items in the cart but they are all null, Which is strange because yesterday they weren’t, now all of a sudden they are null.
Here is my localStorage.js:
export const getCartItems = () => {
const cartItems = localStorage.getItem('cartItems') ?
JSON.parse(localStorage.getItem('cartItems')) : [];
return cartItems;
}
export const setCartItems = (cartItems) => {
localStorage.setItem('cartItems', JSON.stringify(cartItems));
}
Does anyone know what’s going on here? A little help would appreciated