Shubham
Shubham

Reputation: 738

How to update nested objects state of array in redux?

I want to update state of an object in array of array with particular index from the action payload. I have this kind of state in reducers.

const INITIAL_STATE = {
    tasks: {
        taskArray: [
            {
                maintask: 'Main task 1',
                subtask: [
                    {
                        photo_urls: [],
                        task_name: 'Task 1',
                        task_status: false
                    }, 
                    {
                        photo_urls: [],
                        task_name: 'Task 2',
                        task_status: false
                    }
                ]
            },
            {
                maintask: 'Main task 2',
                subtask: [
                    {
                        photo_urls: [],
                        task_name: 'Task 1',
                        task_status: false
                    }, 
                    {
                        photo_urls: [],
                        task_name: 'Task 2',
                        task_status: false
                    }
                ]
            }
        ]
    }
};

export default (state = INITIAL_STATE, action) => {
    switch (action.type) {
        case ON_CHECK_BOX_CLICK:
            return state;

        default:
            return state;
    }
};

I have an object of subtask in action.payload. First I want to check index of an object in array and then I want to update state of particuler array of object.

Upvotes: 1

Views: 111

Answers (1)

Krasimir
Krasimir

Reputation: 13529

I'll suggest to use https://github.com/kolodny/immutability-helper As a payload you may send a result of the update function:

import update from 'immutability-helper';

update(currentState, {
  tasks: {
    tasksArray: {
      0: {
        subtask: {
          1: {
            task_name: { $set: 'New value for Task 2' }
          }
        }
      }
    }
  }
});

Upvotes: 2

Related Questions