S
S
Sanchik972019-12-14 12:10:21
JavaScript
Sanchik97, 2019-12-14 12:10:21

How to change object field value in store array in redux?

The store array stores objects that have a count field. On the CHANGE_ITEM_COUNT event, the count value of a certain element changes depending on the action that comes in the payload along with the id of this element. Now the task is to dynamically update the store array, replacing the old object with a new one and so that the order is preserved. How can this be implemented?

case CHANGE_ITEM_COUNT:

      const itemCount = state.find(({id}) => id === action.payload.id);
      if (action.payload.action === 'decrement' && itemCount.count > 1) {
        itemCount.count--
      }
      if (action.payload.action === 'increment') {
        itemCount.count++
      }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-12-14
@Sanchik97

case CHANGE_ITEM_COUNT:
  return state.map(n => n.id === action.payload.id
    ? {
        ...n,
        count: Math.max(1, n.count + (({
          increment:  1,
          decrement: -1,
        })[action.payload.action]) || 0),
      }
    : n
  );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question