am a newbie in redux, am trying to add an item to the basket but am getting, TypeError: Cannot read properties of undefined (reading 'getState'). why am i not able to get the state is there something i need to do that am not doing, please what am i not doing properly. am using useDispatch hook to read the store and dispatch the action
hey is my code
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
items: [],
}
export const basketSlice = createSlice({
name: "basket",
initialState,
reducers: {
addToBasket: (state, action) => {
state.items = [...state.items, action.payload]
},
removeFromBasket: (state, action) => {},
}
});
export const { addToBasket, removeFromBasket} = basketSlice.actions;
export const selectItems = (state) => state.basket.items;
export default basketSlice.reducer;
import { configureStore } from "@reduxjs/toolkit";
import basketReducer from "../slices/basketSlice";
export const store = configureStore({
reducer: {
basket: basketReducer,
},
});
import '../styles/globals.css'
import { SessionProvider } from "next-auth/react"
import { Provider } from 'react-redux'
import store from '../app/store'
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<Provider store={store}>
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
</Provider>
)
}
import { useDispatch } from 'react-redux'
import {addToBasket} from "../slices/basketSlice"
const Product = ({id, title, description, price, image, category }) => {
const dispatch = useDispatch();
const addItemToBasket = () => {
const product = {
id,
title,
description,
price,
image,
category
}
dispatch(addToBasket(product))
}
return (
<div className="relative flex flex-col m-10 p-10 bg-white rounded-3xl">
<button onClick={addItemToBasket} className=" button">Add to basket</button>
</div>
)
}
export default Product;
It looks like the state isn't being set inside the <Provider />
component correctly. Your store
is a named export, but it's being imported into _app.js
as if it were a default
export (without curly braces). Try using import { store } from "../some_path_to_store"
instead.
Here's a working example to conclude our discussion from the comment section: https://codesandbox.io/s/crazy-fire-o3tr54