Reputation: 11
I am trying to create a reducer to delete object after an action has invoked, but i cant update and save the new object inside my data
Reducer:
export default function deleteCard(state = INITIAL_STATE, action: any) {
if (action.type === 'DELETE_CARD') {
return state.data.filter((card: Card) => card.cardId !== action.id)
} else {
return state
}
}
Action deleteCard
export const deleteCardAction = (id: number) => {
return {
type: 'DELETE_CARD',
id: id
}
}
function handleDeleteCard() <- call the action
const cards = useSelector((state: RootStateOrAny) => state.createCard.data);
const dispatch = useDispatch();
function handleDeleteCard() {
cards.map(({ cardId }: Card) => {
if (cardId === props.activeCard ) {
dispatch(deleteCardAction(cardId))
}
})
}
Initial State:
export const INITIAL_STATE = {
activeCard: 0,
data: [
{
cardId: 0,
cardName: 'Credit card',
cardUsername: 'Vanzo',
cardNumber: '1234 1234 1234 1234',
hideCardNumber: false,
},
]
}
Following error when i try to update:
TypeError: undefined is not an object (evaluating 'state.data.filter')
Upvotes: 1
Views: 522
Reputation: 106
For updating the state you need to return the whole state from reducer something like this:
export default function deleteCard(state = INITIAL_STATE, action: any) {
if (action.type === 'DELETE_CARD') {
return {
...state,
data: state.data.filter((card: Card) => card.cardId !== action.id)
}
} else {
return state
}
}
Upvotes: 1