PPs
PPs

Reputation: 21

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

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));
  };

Upvotes: 2

Views: 1536

Answers (2)

phry
phry

Reputation: 44196

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.

Upvotes: 1

user13937286
user13937286

Reputation:

Because you are importing itemAdd

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

instead of itemAdded

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

Upvotes: 0

Related Questions