UPDATE: I changed the cart, setCart variable to arr, setArr and with the same code, it works fine.
I have a weird issue using useEffect in different components, it works as expected in my functional component that's imported on the home page of my website. However, on the cart page, it doesn't, the state is empty and when I log it I can see there are items in the array but its telling me the length is 0. It looks like this:
[{.},{.},{.}]
The variable I set the local storage to initially logs fine. The problem only happens when I try to set the state.
Here is the useEffect code, its the exact same in both components.
const [cart, setCart] = useState([])
useEffect(() => {
const cart = JSON.parse(localStorage.getItem("cart"))
if (cart !== null) {
setCart(cart)
}
}, [])
The cart variable is coming back as an array so it corresponds with my useState() declaration.
Heres some more code to help. Cart.js
{cart && cart.length > 0 ? (
cart.map((item, index) => {
if (item.quantity > 0) {
return (
<li key={index}>
<span className={styles.itemName}>
{item.name}
<span
className={styles.remove}
onClick={() => removeItem(item)}
>
<FiX /> Remove
</span>
</span>
<span className={styles.quantity}>
<span onClick={() => incrementItem(item)}>
<FiChevronUp />
</span>
<span>{item.quantity}</span>
<span onClick={() => decrementItem(item)}>
<FiChevronDown />
</span>
</span>
<span className={styles.price}>
<span className={styles.priceTotal}>
${(item.price * item.quantity).toFixed(2)}
</span>
<span className={styles.priceEach}>
${item.price} each
</span>
</span>
</li>
)
}
})
) : (
<li>No Items</li>
)}
The cart renders fine on the page itself.