I'm getting this error in my console when i adeded "initialState" to the store
Uncaught SyntaxError: "undefined" is not valid JSON at JSON.parse () at ./src/JS/store/store.js (store.js:6:1) at options.factory (react refresh:6:1) at webpack_require (bootstrap:24:1) at fn (hot module replacement:62:1) at ./src/index.js (Register.js:83:1) at options.factory (react refresh:6:1) at webpack_require (bootstrap:24:1) at startup:7:1 at startup:7:1
i have also a problem with adding an element to the shopping basket, what could be the solution to this problem !
store.js
import { compose, legacy_createStore as createStore } from 'redux';
import { applyMiddleware } from 'redux';
import thunk from "redux-thunk"
import {rootReducer} from "../reducer/index"
const cartItemsFromStorage = localStorage.getItem('cartItems')
? JSON.parse(localStorage.getItem('cartItems'))
: [];
const initialState = {
cart: {
cartItems: cartItemsFromStorage,
},
};
const middleware = [thunk];
export const store = createStore(
rootReducer,
initialState,
compose(applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
)
shopReducer
import { ADD_TO_CART} from "../constant/actionType"
const initialState = {
cartItems: [],
};
export const shopReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
const item = action.payload;
const existItem = state.cartItems.find((x) => x.product === item.product);
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;
}
};
shopActions
import { ADD_TO_CART} from "../constant/actionType"
import axios from 'axios'
export const addToCart = (id) => async(dispatch, getState)=>{
const { data } = await axios.get(`/api/product/${id}`);
try {
dispatch({
type: ADD_TO_CART,
payload: {
id: data._id,
name: data.name,
image: data.image,
price: data.price,
}}) ;
localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems))
} catch (error) {
console.log(error)
}
}