Home > Mobile >  ReactJS - localstorage did not update after refresh the page
ReactJS - localstorage did not update after refresh the page

Time:06-27

im new here, can somebody help me to solve this. why my localstorage on my redux did not update after i try to remove the state from cartItems? so everytime i remove the cart, and i refresh.. localstorage did not return the new value. can somebody help me and explain this? pls help

cartSlice.js

export const cartRemove = createAsyncThunk(
  'cartRemove/remove',
  async (id, thunkAPI) => {
    try {
      const res = await axios.get(`http://localhost:8000/api/products/${id}`);
      const data = await res.data;
      console.log(data._id);
      thunkAPI.dispatch(removeCart(data._id));
      return localStorage.setItem(
        'cartItems',
        JSON.stringify(thunkAPI.getState().cart.cartItems)
      );
    } catch (error) {}
  }
);

const cartSlice = createSlice({
  name: 'cart',
  initialState: {
    cartItems: localStorage.getItem('cartItems')
      ? JSON.parse(localStorage.getItem('cartItems'))
      : [],
  },
  reducers: {
removeCart: (state, action) => {
      return {
        ...state,
        cartItems: state.cartItems.filter(
          (elem) => elem.product !== action.payload
        ),
      };
    },
export default cartSlice.reducer;
export const { addCart, removeCart } = cartSlice.actions;

cartScreen.jsx

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import { useLocation, useParams } from 'react-router-dom';
import Message from '../components/Message';
import { addToCart, cartRemove, removeCart } from '../redux/cartSlice';

const CartScreen = () => {
  const dispatch = useDispatch();
  const { cartItems } = useSelector((state) => state.cart);
  const { id } = useParams();
  const navigate = useNavigate();
  let qty = useLocation().search;
  qty = qty ? qty.split('=')[1] * 1 : 1;

  useEffect(() => {
    if (id) {
      dispatch(addToCart({ id, qty }));
    }
  }, [dispatch, qty, id]);

  const removeFromCartHandler = (id) => {
    dispatch(cartRemove(id));
  };

CodePudding user response:

Problem is in your thunk, in this part:

thunkAPI.dispatch(removeCart(data._id));
return localStorage.setItem(
    'cartItems',
    JSON.stringify(thunkAPI.getState().cart.cartItems)
  )

You are basically trying to update redux state and immediately after to access that new state, but thunkAPI.getState().cart.cartItems returns old state, from closure, instead of new one(as you were expecting), and thats why you always update local storage with old, instead with new state. Solution would be to move local storage setter in removeCart slicer reducer, or if you wish to stick with the current solution, to do something like:

export const cartRemove = createAsyncThunk(
  'cartRemove/remove',
  async (id, thunkAPI) => {
    try {
      const res = await axios.get(`http://localhost:8000/api/products/${id}`);
      const data = await res.data;
      console.log(data._id);
      thunkAPI.dispatch(removeCart(data._id));
      const updatedCart = thunkAPI.getState().cart.cartItems.filter(i => i.product !== data._id);
      return localStorage.setItem(
        'cartItems',
        JSON.stringify(updatedCart)
      );
    } catch (error) {}
  }
);
  • Related