Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect hook not running to update the local storage

I am Creating an E-commerce website using React, and I am setting the cart items (which the user has selected to add to his/her cart) in the localStorage on page load and then getting them using localStorage.getItems().

But for some reason when I am trying set Items to localStorage using the useEffect hook then it’s not running I don’t know why. I even tried to console.log(), but that is also not running.

And because of that when the function which gets the item from localStorage runs it returns null.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the code please help me out.

import { createContext, useContext, useReducer, useEffect } from "react";
import { reducer } from "../reducer/CartReducer";

// creating Context using context API
const CartContext = createContext();


const getLocalCartData = () => { // this function returns null because useEffect did not run and not set  any thing to the localstorage.
  let localCartData = localStorage.getItem('CartItems');
  console.log(localCartData)
  if (localCartData === []) {
    return [];
  } else {
    return JSON.parse(localCartData);
  }
}

// Defining initial State for the useReducer
const initialState = {
  cart: getLocalCartData(),
  total_item: ""
}
const CartProvider = ({ children }) => {

  // Defining useReducer, dispatch, state  
  const [state, dispatch] = useReducer(reducer, initialState);

  // Add products to cart
  const addToCart = (MainProduct, amount) => {
    dispatch({ type: "ADD_TO_CART", payload: { MainProduct, amount } });
  };

  // Add products to cart
  const removeItem = (id) => {
    dispatch({ type: "REMOVE_ITEM", payload: id });
  };

  // Decreament Product Quantity
  const setDecreament = (id) => {
    dispatch({ type: "SET_DECREAMENT", payload: id })
  }

  // Increament Product Quantity
  const setIncreament = (id) => {
    dispatch({ type: "SET_INCREAMENT", payload: id })
  }

  useEffect(() => { // this one useEffect is not running 
    console.log("It Should run here")
    localStorage.setItem('CartItems', JSON.stringify(state.cart));   
  }, [])

  // Creating the Provider
  return (<CartContext.Provider value={{ ...state, addToCart, removeItem, setIncreament, setDecreament }}>
    {children}
  </CartContext.Provider>);
}

// Creating use context API
const useCartContext = () => {
  return useContext(CartContext);
}

export { CartProvider, useCartContext };

>Solution :

First of all, this if (localCartData === []) will never be true. I think you wanted to check if there is nothing in the storage, if so, it should be if (!localCartData).

Then, your useEffect, because it has an empty dependency array, will run only once, on the mount. You would wanna add state as a dependency:

useEffect(() => { 
  console.log("It Should run here")
  localStorage.setItem('CartItems', JSON.stringify(state.cart));   
}, [state])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading