I am trying to add products to shopping cart by storing them in local storage but, they are not getting stored. I looked into Redux-dev-tools and found out my state is not updating:
As you can see action is getting fired but my state is not updating:
Here is the source code:
cartAction.js
import axios from "axios"; import { CART_ADD_ITEM, CART_REMOVE_ITEM } from "../constants/cartConstants"; export const addToCart = (id, qty) => async (dispatch, getState) => { const { data } = await axios.get(`/api/product/${id}`); dispatch({ type: CART_ADD_ITEM, payload: { productID: data.product._id, name: data.product.name, image: data.product.image, price: data.product.price, countInStock: data.product.countInStock, qty, }, }); localStorage.setItem("cartItems", JSON.stringify(getState().cart.cartItems)); };
cartReducer.js
import { CART_ADD_ITEM, CART_REMOVE_ITEM } from "../constants/cartConstants"; export const cartReducer = (state = { cartItems: [] }, action) => { switch (action.state) { case CART_ADD_ITEM: const item = action.payload; const existItem = state.cartItems.find( (x) => x.productID === item.productID ); if (existItem) { return { ...state, cartItems: state.cartItems.map((x) => x.productID === existItem.productID ? item : x ), }; } else { return { ...state, cartItems: [...state.cartItems, item], }; } // case CART_REMOVE_ITEM: // return {}; default: return state; } };
store.js
import { createStore, combineReducers, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import { composeWithDevTools } from "redux-devtools-extension"; // reducers import { productDetailsReducer, productListReducer, } from "./reducers/productReducers"; import { cartReducer } from "./reducers/cartReducers"; const reducer = combineReducers({ productList: productListReducer, productDetails: productDetailsReducer, cart: cartReducer, }); const cartItemsFromStorage = localStorage.getItem("cartItems") ? JSON.parse(localStorage.getItem("cartItems")) : []; const initialState = { cart: { cartItems: cartItemsFromStorage }, }; const middleware = [thunk]; const store = createStore( reducer, initialState, composeWithDevTools(applyMiddleware(...middleware)) ); export default store;
CartScreen.js
import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { addToCart, removeFromCart } from "../../redux/actions/cartActions"; import { Link } from "react-router-dom"; import ErrorMessage from "../../components/ErrorMessage/ErrorMessage"; import "./CartScreen.scss"; const CartScreen = ({ match, location, history }) => { const productID = match.params.id; const qty = location.search ? Number(location.search.split("=")[1]) : 1; const dispatch = useDispatch(); const cart = useSelector((state) => state.cart); const { cartItems } = cart; console.log(cartItems); useEffect(() => { if (productID) { dispatch(addToCart(productID, qty)); } }, [dispatch, productID, qty]); return ( <> <h1>Shopping Cart</h1> </> ); }; export default CartScreen;
Advertisement
Answer
You need to fix this on CartReducer.js
switch (action.state) {
to
switch (action.type) {