react / redux toolkit useSelector not updating when store state changed

Viewed 1401

hi i have a cart slice and when i push objects to it with disptach state gets updated but when mapping it in the cart component to display it as a list it doesnt get updated ! m a noobie forgive me if m doing smth stupid!

cart slice :

       import { createSlice } from '@reduxjs/toolkit'
const CartSlice = createSlice({
  name: 'cart',
  initialState: {
    cart:[{name:"cart item",price:"15",qt:1},]
  },
  reducers: {
    additem: (state,action) => {
      state.cart=[...state.cart,action.payload]
    },
   
}
})

export const {additem} = CartSlice.actions

export default CartSlice.reducer

store :

import { configureStore } from '@reduxjs/toolkit'
import RestaurantsReducer from './Slices/RestaurantsSlice'
import CartReducer from './Slices/CartSlice'
export default configureStore({
  reducer: {
      Restaurant:RestaurantsReducer,
      Cart:CartReducer
  },
})

cart component:

import React from "react";
import { useSelector } from "react-redux";
import {ListGroup} from 'react-bootstrap'
function Cart() {
  let items = useSelector((state) => state.Cart.cart);
  console.log(items)
  return (
    <div>
      <ListGroup>
        {items.map((item) => (
          <ListGroup.Item>{item.name} {item.price} * {item.qt}</ListGroup.Item>
        ))}
      </ListGroup>
    </div>
  );
}

export default Cart;

crat item are being pushed this way :

const dispatch=useDispatch();
dispatch(additem({name:item.name,price:item.price,qt:1}))
1 Answers

According to the documentation examples the state passed to your reducer function seems to be an immer object so you can do the following:

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

As documented in the immer documentation.

Related