Reputation: 748
Here is my reducer
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:
???
return x
default:
}
return state;
};
Can some one help me how can I remove current item from array? I have tried many ways but I don't understand what the problem here, also I have used react-addons-update for update store
Upvotes: 4
Views: 105
Reputation: 697
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
Upvotes: 1
Reputation: 31024
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)
}
Upvotes: 4
Reputation: 36985
Instead of splice
ing, 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)
]
Upvotes: 0