arraysreduxtoolkit

Redux Toolkit remove an item from array (Everything is being deleted)


I am trying to make a system like shopping cart with redux and react. The products are stored in a redux slice array as a whole object. The product object goes like this:

enter image description here

This is my code for my checkbox input

  const products = useSelector((state) => state.prodSlice.value)

  const handleChange = (event) => {
    const button = event.target
    const isActive = button.checked
    const itemName = event.currentTarget.id
    const items = products.items

    const itemsArr = {}

    items.forEach((items) => {
      if (items.productName === itemName) {
        itemsArr['productName'] = items.productName
        itemsArr['total'] = items.total
        itemsArr['quantity'] = items.quantity

        if (isActive) {
          dispatch(checkout({products: itemsArr}))
        } else {
          dispatch(removeItem({products: itemsArr}))
        }

      }
    })
  }

When adding products to the array, there is no problem,

enter image description here

However, when I uncheck an item, and get the value of array it returns just an empty array instead of removing just 1 item.

enter image description here

I just want to delete that one item from the array, here is my redux slice code

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

const initialState = {
    value: {
        products: [],
    }
}

export const checkOut = createSlice({
    name: "checkout",
    initialState,
    reducers: {
        checkout: (state, action) => {
            state.value.products.push(action.payload)
        },
        removeItem: (state, action) => {
            state.value.products = state.value.products.filter((products) => products.produdctName !== action.payload.productName)

        }
    }
})

export const { checkout, removeItem } = checkOut.actions
export default checkOut.reducer

I hope someone can help me pls


Solution

  • your removeItem reducer should simply return the filtered array

     removeItem: (state, action) => {
                return state.value.products.filter((products) => products.productName !== action.payload.productName)
            }