0

I have a question regarding Redux and updating a value of a nested object.

Let's say this is my initial state:

const INITIAL_STATE = {
 columnState: {
  1: {
    loading: false
  },
  2: {
    loading: false
  }
 }
};

When my reducer is called:

case COLUMN_STATE_UPDATE:
    const { type } = payload;
    return {
       ...state
    }
}

How do I update the value of loading for the particular id? Let's say that I update entry with key = 2, how do I change the value of loading to true for columnState object with key 2, and return the new state?

2 Answers 2

2

If your COLUMN_STATE_UPDATE action is updating only the columnState part (assuming type in your payload as the key):

case COLUMN_STATE_UPDATE:
    const { type } = payload;
    return {
       ...state,                     // keep the other keys as they were
       [type]: {                     // only update the particular one
           loading: true 
       }
    }
}

If your COLUMN_STATE_UPDATE action is updating the entire state that looks like INITIAL_STATE (again, assuming type in your payload as the key):

case COLUMN_STATE_UPDATE:
    const { type } = payload;
    return {
       ...state,                     // keep the other keys of state as they were
       columnState: {
           ...state.columnState,     // keep the other keys of columnState as they were
           [type]: {                 // only update the particular one
               loading: true
           }
       }

    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works great! Thanks
1
case COLUMN_STATE_UPDATE:
// payload = {type: 1, 1: {loading: true}}
    const {type} = payload;
    return {
       columnState: {...state.columnState, [type]: payload[type] }}
};

The above could be implemented as:

/**
   * @param {Object} state The Global State Object of shape:
   * @example
   * const INITIAL_STATE = {
   *     columnState: {
   *         1: {
   *             loading: false
   *         },
   *         2: {
   *             loading: false
   *         }
   *     }
   * };
   * @param {Object} action The Action Object of shape
   * @example 
   * let action = {type: 1, 1: {loading: true}};
   * @returns {Function} The "slice reducer" function.
   */

function columnStateUpdate(state = {}, action) {
    const {type} = action;
    switch(type) {
        case COLUMN_STATE_UPDATE:   
        return {
            columnState: {...state.columnState, [type]: action[type] }}
        };
    }
}

I use action instead of payload because (state, action) is standard naming convention used in Redux Docs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.