Home > OS >  Why my dispatch won't change the state? "Redux Toolkit"
Why my dispatch won't change the state? "Redux Toolkit"

Time:07-13

I'm practicing Redux and in my project when i dispatch an action i will see that in the dev tools but the state won't change and it will remain an empty Array. why is this happening ? i will appreciate a little help

shopping cart.js

import { createSlice, createAction } from "@reduxjs/toolkit";

// Action Creator

export const itemAdd = createAction("products/itemAdded");

const slice = createSlice({
  name: "shoppingCart",
  initialState: [],
  reducers: {
    itemAdded: (cart, action) => cart.push(action.payload),
  },
});

export const { itemAdded} = slice.actions;
export default slice.reducer;


Dispatch

import { useDispatch, useSelector } from "react-redux";
import { itemAdd } from "../../store/state/shoppingCart";

// It's an onClick Event Handler 
  const handleAddItem = (item) => {
    dispatch(itemAdd(item));
  };

CodePudding user response:

Also, your reducer needs braces.

    itemAdded: (cart, action) => { cart.push(action.payload) }

Otherwise it will return the return value of cart.push, which is the new length of the array - and immer can't do its work if you modify the state and return something unrelated at the same time.

CodePudding user response:

Because you are importing itemAdd

import { itemAdd } from "../../store/state/shoppingCart";

instead of itemAdded

import { itemAdded } from "../../store/state/shoppingCart";
  • Related