1

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.

Darren
  • 37
  • 6
  • Need more steps to reproduce this. Are you able to try setting a debugger in this code to check localstorage? How are you rendering the components? – Dana Woodman Apr 20 '20 at 18:30
  • Not sure how to go about setting a debugger in react/gatsby code, let me take a look. I am actually rendering the code from 'cart' after the fact and it renders fine (using map). I have 3 other functions to increment/decrement quantity and remove items from the cart but I can't do them anymore it because there's 'nothing' in state. I should add this all worked fine in a regular class component. I need hooks for Stripe. – Darren Apr 20 '20 at 18:58
  • You should add the section of code where it shows how you're using `cart` in the render. Also check if `JSON.parse(localStorage.getItem("cart"))` is also an array just like what you initialized `cart` with – bilwit Apr 20 '20 at 19:06
  • I added some edits to the post. – Darren Apr 20 '20 at 19:21
  • So, to make sure I got it right. From localstorage you get an array that has elements, but when updating the state, u still have an empty array, is that right? – Adrian Pascu Apr 20 '20 at 20:39
  • @AdrianPascu Yeah that's correct! – Darren Apr 20 '20 at 21:02
  • Try renaming the variable you put your localStorageRespone into. I know scope variable has priority,but that could be one cause. Also,console log your cart(the local one,not the state) right before calling setCart to check the data it holds – Adrian Pascu Apr 20 '20 at 21:26
  • Wait,no found the problem – Adrian Pascu Apr 20 '20 at 21:26
  • You are calling setCart inside an if block which shouldn't be done with hooks – Adrian Pascu Apr 20 '20 at 21:27
  • @AdrianPascu why do you say that? – Dana Woodman Apr 21 '20 at 14:20
  • So don't know what happened but I reverted back to an older version of the repo when it worked (with the same code) and it works fine now. I am going to clean up my code now and see if it happens again. – Darren Apr 21 '20 at 14:56

0 Answers0