skip to Main Content

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


  1. Use

    import basketReducer from "./Slices/basketSlice";
    

    in Store.js to import the default export as basketReducer. The way you have it now attempts to import an exported symbol named basketReducer, which doesn’t exist. Alternatively, you could use

    export const basketReducer = basketSlice.reducer;
    

    in Slices/basketSlice.js to export the reducer under the name you’re importing.

    Login or Signup to reply.
  2. Try this within the component where you want to use this state

    import { useSelector } from "react-redux";
    const component = () => {
      const selectItems = (state) => 
      useSelector((state)=>state.basket.items);
      return <></>;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search