Search code examples
reduxreact-reduxonclick

Uncaught Error: When called with an action of type "DELITEM", the slice reducer for key "addItem" returned undefined


Uncaught Error: When called with an action of type "DELITEM", the slice reducer for key "addItem" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.

What is this error when I open inspection. My problem is that Onclick is not working in my app.

Here is the code:

   import React from 'react'
import { useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'
import { delItem } from '../redux/actions/index'
import { NavLink } from 'react-router-dom'



const Cart = () => {

const state = useSelector((state)=> state.addItem)
const dispatch = useDispatch()

const handleClose = (item) => {
    dispatch(delItem(item))
}

const cartItems = (cartItem) => {
    return(
            <div className="px-4 my-5 bg-light rounded-3" key={cartItem.id}>
                <div className="container py-4">
                    <button onClick={()=>handleClose(cartItem)} type="button" className="btn-close float-end" aria-label="Close"></button>
                    <div className="row justify-content-center">
                        <div className="col-md-4">
                            <img src={cartItem.image} alt={cartItem.title} height="200px" width="180px" />
                        </div>
                        <div className="col-md-4">
                            <h3>{cartItem.title}</h3>
                            <p className="lead fw-bold">${cartItem.price}</p>
                        </div>
                    </div>
                </div>
            </div>
        );
}

Solution

  • case "DELITEM": return 
                return state = state.filter((x)=>{
                    return x.id !== action.payload.id
                })
    

    change above code to :

    make it to "DELITEM": return [...state.filter((x)=>{
                    return x.id !== action.payload.id
                })]