1

I have a state array that I want to delete an object from. For example, I have:

[
 {
  name:'bench',
  weight: 200
 },
{
  name:'squat',
  weight: 300
 },
]

I want to give the user the option to delete an exercise if they wanted to, but I can't figure out how. Here is my reducer:

const initialState = [];

const movementReducer = (state = initialState, action) => {
    switch (action.type) {
        case ADD_MOVEMENT: 
            return [ 
                ...state, action.payload
            ];
        case UPDATE_MOVEMENT:
            return [
                ...state.map(item => item.movementName === action.payload.movementName ? action.payload : item  )
            ];
        case DELETE_MOVEMENT:
            return [
                state.filter(item => item.movementName === action.payload.movementName ? "true" : "false"  )
            ];
        default:
            return state;
    }
};

export default movementReducer;

With the code I have now, I get nothing returned on the page, but I can still see my state in my redux devtools, meaning it's still there. Any help?

0

1 Answer 1

1

In you're filter you're returning "true" or "false" from your comparison, but both those values are truthy: e.g. Boolean("false") === true.

Change your movement reducer to look like:

const movementReducer = (state = initialState, action) => {
    switch (action.type) {
        case ADD_MOVEMENT: 
            return [ 
                ...state, action.payload
            ];
        case UPDATE_MOVEMENT:
            return [
                ...state.map(item => item.movementName === action.payload.movementName ? action.payload : item  )
            ];
        case DELETE_MOVEMENT:
            return [
                ...state.filter(item => item.movementName === action.payload.movementName)
            ];
        default:
            return state;
    }
};

I simplified the filter function as having a ternary was redundant.

As a note, this function is comparing the movementName prop as that's what the original code had, but the code example you provided for those items used name as the prop. I am not sure which one is correct but be sure they match 😀

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.