H
H
Hazrat Hajikerimov2017-06-22 14:19:28
React
Hazrat Hajikerimov, 2017-06-22 14:19:28

How to immutably remove a property from an array in a reducer?

There is an initial state:

const initialState = {
  products: [
    { id: 5 },
    { id: 7 }
  ]
}

And when an action to remove a product with id: 7 from the cart occurs, you must remove the property from the state.
Below is an example solution, but how immutable is it?
function (state = initialState, action) {
  case REMOVE_PRODUCT_CART:
    return {
      ...state,
      products: state.products.filter(item => item.id !== action.payload)
    } 
}

And also enlighten me, in reducers by convention (flux architecture) there can be only one pure function that is returned by default, or you can produce there (naturally the most necessary) functions, for example, for reuse, add a function that is given in the redux documentation
function removeItem(array, action) {
    return array.filter( (item, index) => index !== action.index);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2017-06-22
@hazratgs

Below is an example solution, but how immutable is it?

This is perfect: filter creates a new array.
You can use helpers (the same lodash \ ramda). The main thing is that in the end your reducer should be a pure function without side effects (this means that all the functions that you use inside must also be pure).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question