0

How do I update state of a nested array of object to add any empty object using typescript? I want to add to the bottomlevels in level object

how I want final state to look.

const data = {
  level: {
    subLevels: [
      {
        bottomLevels: [
          {
            ...
          },
        ],
      },
      {
        bottomLevels: [
          {
            //I want to update the data here
          },
        ],
      },
    ],
  },
};

types

  type LevelDataType = {
    id: number;
    name: string;
    subLevels?: SubLevelDataType[];
  };
    
   type SubLevelDataType = {
     id: number;
     name: string;
     bottomLevels?: BottomLevelsDataType[];
     subLevelId: number;
   };
    
  type BottomLevelsDataType = {
    id: number;
    name: string;
    SubLevelId: number;
};

state

this.state = {
 newData: {
        level: {} as LevelDataType,
        subLevels: [],
        BottomLevels: [],
      }
}

set state when I try to go down to a nested array object in bottomLevels to add an empty obj it doesnt let me

    this.setState({
            newData: {
              ...this.state.newData,
              level: [
                   ...this.state.newData.level,
                   subLevels:[
                             ...this.state.newData.level.subLevels,
                       bottomLevels:[
                                    ...this.state.newData.level.subLevels.bottomLevels,
                                    {} as bottomLevelsType
                     ]
                  ]
    
              
              ],
            },
          });
endlessCode
  • 1,255
  • 4
  • 21
  • 36
  • You cannot have key value pairs in array. You can check how spread works in different context (array/object): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax To answer your question, since `subLevels` is an array, you first need to find the index you want to update. Same for `bottomLevels`. You can check out this post for updating at specific index: https://stackoverflow.com/questions/28121272/whats-the-best-way-to-update-an-object-in-an-array-in-reactjs – vighnesh153 Sep 28 '22 at 05:04
  • On a side note, avoid this deep nesting of objects as it might lead to problems later on when the application grows. Try to keep your react state as flat as possible and as small as you can. You can maybe split the state the same way how you would design a relational DB and associate different states together using some kind of IDs. – vighnesh153 Sep 28 '22 at 05:06

0 Answers0