P
P
PlasterTom2018-06-29 15:29:24
React
PlasterTom, 2018-06-29 15:29:24

How to change nested properties in redux?

It is necessary to change the semi-qty of one of the array elements, this element is transferred to the payload action
//an array of objects

items = [
   {
        id: '1',
        desc: 'Some description',
        qty: 1
    },
  {
        id: '2',
        desc: 'Another description',
        qty: 1,
    },
и т.д.

//action
export const incrementQty = (item) => {
    return {
        type: INCREMENT_QTY,
        payload: item
    }
};

//reducer with an error
const initialState = {
    items: items
};

export default function(state = initialState, action) {
    const {type, payload} = action;

    switch (type) {
        case INCREMENT_QTY:
          const newItem =   state.items.filter(item => item === payload);
          return {
              ...state,
              newItem: {
                  ...newItem,
                  [newItem.qty]: 10
                  }
              };
        default:
            return state
    }
}

I know that when changing nested data, it is necessary to make copies at all levels of nesting.
Parsed an example from the documentation:
function updateVeryNestedField(state, action) {
    return {
        ...state,
        first : {
            ...state.first,
            second : {
                ...state.first.second,
                [action.someId] : {
                    ...state.first.second[action.someId],
                    fourth : action.someValue
                }
            }
        }
    }
}

And my code above is an attempt to repeat the correct approach described in the documentation. But I can’t, I’m doing something wrong, I clearly don’t understand something in this process. Can someone explain what is my mistake? I expect at the output that the value of the qty field will change, but I get the following
items in state: [here is an array of items objects without any changes]
newItem.undefined: 10 - a new field in the state
P.S. I am also aware of immutable.js and immutability-helper and plan to use these solutions in the future. But in this example, I would like to understand without them and understand what is happening in the code.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
davidnum95, 2018-06-29
@PlasterTom

case INCREMENT_QTY:
    const { payload: newItem } = action;
    return {
      ...state,
      items: state.items.map(item => {
        if(item.id === newItem.id) {
          return {
            ...item,
            qty: newItem.qty,
          }
        }
        return item;
      })
    };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question