score:4

Accepted answer

i think that array.prototype.filter would be the most easy and readable solution to remove an item from an array:

return {
  pros: state.filter((item, index) => index !== action.index)
}

score:0

instead of spliceing, just slice the array before the index, after the index, and return the combined array.

it'd keep the original array untouched

  [
    ...state.pros.slice(0, action.index),
    ...state.pros.slice(action.index + 1)
  ]

score:1

i think this should do the trick ( haven't tested )

you need to create a copy of the array, remove the item, and then assign the new array to the state

const initialstate = {
pros: [''],
}

export const rootreducer = (state = initialstate, action) => {
switch (action.type) {
    case action_add_pros:
    return {
        ...state.pros,
        pros: [...state.pros,  action.payload]
        }

    case action_change_pros:
    return update(state, { 
        pros: { 
        [action.index]: {
            $set: action.payload
        }}
    });

    case action_remove_pros:
    // make a copy of the array
    const newarr = state.pros
    // remove item at index 4
    newarr.splice(newarr.indexof(action.payload), 1)   

    return update(state, {
           pros: [...newarr]
    })

   //this is the old code that is incorrect
   /* return update(state, { 
        pros: { 
        [action.index]: {
            $set: newarr
        }}
    });/*


    return x
    default:
}
return state;
};

for more information about the array.splice()

remember: never edit the state directly. the state needs to be immutable

edit: the return method was wrong, please try this one edit: as from your comment, i corrected the newarr also now it should remove the "current" value from the array basically you wan't to edit the copy of the array and then just assign the smaller array


Related Query

More Query from same tag