D
D
d22072020-07-22 13:46:54
React
d2207, 2020-07-22 13:46:54

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 filterwhich 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;
    }
}


render in App.js:

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>
        );
    }


state looks like:

const initialState = [
     {
        name: 'Theodore Roosevelt',
        age: 56
    },
];

export default initialState;

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2020-07-22
@d2207

case 'DELETE_ITEM':
  return state.filter(n => n.name !== action.name);

D
d2207, 2020-07-22
@d2207

In short, I do not know how, but the operation of the method filterremains 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))
            ];

M
Mikhail Osher, 2020-07-22
@miraage

case 'DELETE_ITEM'
  return state.filter(item => item.name !== action.name);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question