Reputation: 327
I am learning REDUX and REDUX TOOLKIT and I get this error in my App.
Uncaught Error: The slice reducer for key "cart" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.
at redux.js:473:1
at Array.forEach (<anonymous>)
at assertReducerShape (redux.js:466:1)
at combineReducers (redux.js:531:1)
at configureStore (configureStore.ts:147:1)
at ./src/store/index.js (index.js:5: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 (Products.js:59:1)
In my store, I have this cartSlice.js file.
import { createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
name: "cart",
initialValue: { itemsList: [], totalQuantity: 0, showCart: false },
reducers: {
addToCart(state, action) {
const newItem = action.payload;
//check if Item is available
const existingItem = state.itemsList.find((item) => {
return item.id === newItem.id;
});
if (existingItem) {
existingItem.quantity++;
existingItem.price += newItem.price;
} else {
state.itemsList.push({
id: newItem.id,
price: newItem.price,
quantity: 1,
totalPrice: newItem.price,
name: newItem.name,
});
}
},
removeFromCart() {},
setShowCart(state) {
state.showCart = true;
},
},
});
export const cartActions = cartSlice.actions;
export default cartSlice;
This is the related Product.js file.
import React from "react";
import "./Product.css";
import { useDispatch, useSelector } from "react-redux";
import { cartActions } from "../store/cartSlice";
const Product = ({ name, id, imgURL, price }) => {
const dispatch = useDispatch();
const cartItems = useSelector((state) => state.cart.itemsList);
console.log(cartItems);
const addToCart = () => {
dispatch(
cartActions.addToCart({
name,
id,
price,
})
);
};
return (
<div className="card">
<img src={imgURL} alt={name} />
<h2>{name}</h2>
<p>$ {price}</p>
<button onClick={addToCart}>Add to cart</button>
</div>
);
};
export default Product;
I have no idea why I get this ERROR. Please help. I have found a similar question, but it is related to REDUX. Mine one is related to REDUX TOOLKIT.
react The slice reducer for key "mods" returned undefined during initialization. (redux)
Thank you for your reply.
Upvotes: 3
Views: 1978
Reputation: 327
The reply is rather simple. I have used
initialValue: { itemsList: [], totalQuantity: 0, showCart: false },
Instead, I should used
initialState: { itemsList: [], totalQuantity: 0, showCart: false },
Upvotes: 2