Make a "DeleteTransaction" case and remove an item from the state using filter

I want to make a DeleteTransaction case and remove an item from the state using filter.

My current code is below:

const TransactionReducer = ((state, action) => {
    switch(action.type){
        case "AddTransactions": {
            return [action.payload, ...state]
        }
        default:
            return state;
    }
})

export default TransactionReducer;

Solution 1:

You can create a new case and filter() your state. filter() returns a new array, so the following should work:

const TransactionReducer = ((state, action) => {
    switch(action.type) {
        case "AddTransactions": 
            return [action.payload, ...state]
        
        case "DeleteTransaction": 
            return state.filter(item => item.id !== action.payload)
        
        default:
            return state;
    }
})

export default TransactionReducer;

You can pass an id as the payload and check if it's the same as the id in your state array. (Although I don't know how your state looks like, so it's just a guess.)