Answer the question
In order to leave comments, you need to log in
How to remove entities from Redux?
Hello everyone, I'm learning redux, I wrote cases for adding and removing entities. The deletion does not work, the logic seems to be correct, we take the whole ...state
, use the method on it filter
which returns a new array consisting of elements that satisfy the condition, i.e. from elements not equal to action.name
. Thus, we removed the desired entity from the array + created a new array, and did not mutate the old one, everything seems to be correct, but why doesn’t it work?
reducer
export default function reducer(state = initialState, action) {
switch (action.type) {
case 'ADD_ITEM':
return [
...state,
{
name: action.name,
age: action.age
}
];
case 'DELETE_ITEM':
return [
...state,
state.filter(name => name!== action.name),
];
default:
return state;
}
}
function ListOfUsers() {
const listItems = users.map(function (value, index) {
return (
<div>
<li key={index}>{value.name}, {value.age}</li>
<button onClick={() => dispatch({ type: 'DELETE_ITEM', name:value.name })}
className="btn btn-danger btn-sm">
Удалить
</button>
</div>
)
});
return (
<ul>{listItems}</ul>
);
}
const initialState = [
{
name: 'Theodore Roosevelt',
age: 56
},
];
export default initialState;
Answer the question
In order to leave comments, you need to log in
In short, I do not know how, but the operation of the method filter
remains a mystery. If someone could explain I would be very grateful. Remade using concat and slice.
return [
...state.slice(0, action.id).concat(state.slice(action.id + 1))
];
case 'DELETE_ITEM'
return state.filter(item => item.name !== action.name);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question