In my e-commerce web in Nextjs i am trying to implement add to basket functionality using redux but the error "Cannot read properties of undefined (reading ‘items’): export const selectItems = (state) => state.basket.items;" keeps on occuring.Below is my code
Store.js
import { configureStore } from "@reduxjs/toolkit";
import { basketReducer } from "./Slices/basketSlice";
export const store = configureStore({
reducer: {
basket: basketReducer,
},
});
Slices/basketSlice.js
import { createSlice } from "@reduxjs/toolkit";
// const initialState = {
// items: [],
// };
export const basketSlice = createSlice({
name: "basket",
initialState: { items: [] },
reducers: {
addToBasket: (state, action) => {
state.items = [...state.items, action.payload];
},
removeFromBasket: (state, action) => {},
},
});
// Action creators are generated for each case reducer function
export const { addToBasket, removeFromBasket } = basketSlice.actions;
export const selectItems = (state) => state.basket.items;
export default basketSlice.reducer;
2
Answers
Use
in
Store.js
to import the default export asbasketReducer
. The way you have it now attempts to import an exported symbol namedbasketReducer
, which doesn’t exist. Alternatively, you could usein
Slices/basketSlice.js
to export the reducer under the name you’re importing.Try this within the component where you want to use this state