'why am i not getting the state in my application
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;
Solution 1:[1]
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
Solution 2:[2]
Either return NEW state from action reducer:
addToBasket: (state, action) => {
return { ...state, items: [...state.items, action.payload] }
},
or MODIFY existing state without replacing it. And don't return anything:
addToBasket: (state, action) => {
state.items.push(action.payload)
},
also, in your example provide a type information for an action:
action: PayloadAction<type_of_item>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark G |
| Solution 2 | Andrej Kireje? |
