I was a following a MERN STACK tutorial and while setting my cart This is the error I am getting but, I console.log the data in my reducer and it's showing but don't know why is it showing this error
Unhandled Rejection (TypeError): state.cartItems is undefined
Also, why is the tutor using localStorage for storing data , Can't we directly send it to reducer after fetching Cart Action... How is it related
Thank You
CART ACTION
import { ADD_TO_CART } from '../constants/CartConstants';
import axios from "axios";
export const addToCart = (id, qty) => async (dispatch, getState) => {
const { data } = await axios.get(`/api/products/${id}`);
dispatch({
type: ADD_TO_CART,
payload: {
product: data._id,
name: data.name,
image: data.image,
price: data.price,
countInStock: data.countInStock,
qty
}
})
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))
STORE
import {createStore , applyMiddleware, combineReducers} from 'redux';
import thunk from 'redux-thunk'
import {composeWithDevTools} from 'redux-devtools-extension';
import {productListReducer , productDetailsReducer } from './reducers/productReducer' ;
import {cartReducer} from "./reducers/cartReducer"
const reducer = combineReducers({
productList: productListReducer,
productDetails:productDetailsReducer,
cart: cartReducer
});
const cartItemsFromStorage = localStorage.getItem('cartItems') ? JSON.parse(localStorage.getItem('cartItems')) : []
const initialState = {
cart: cartItemsFromStorage
};
const middleware = [thunk];
const store = createStore(reducer , initialState , composeWithDevTools(applyMiddleware(...middleware)))
//composite with dev tools is used to connect our store with our devtools
export default store;
CART REDUCER
import { ADD_TO_CART } from '../constants/CartConstants';
export const cartReducer = (state = { cartItems: [] }, action) => {
switch (action.type) {
case ADD_TO_CART:
const item = action.payload;
const existItem = state.cartItems.find((x) => x.product === item.product)
console.log(existItem)
if (existItem) {
return {
...state,
cartItems: state.cartItems.map(x => x.product === existItem.product ? item : x)
}
} else {
return {
...state,
cartItems: [...state.cartItems, item]
}
}
default:
return state
}
}
i know it is an old question,but in case someone is facing the same problem, the answer is
to replace this:
const initialState = {cart: cartItemsFromStorage};
with this:
const initialState = { cart: { cartItems: cartItemsFromStorage } };
in the store.js