0

I'm currently try to update the state object inside of my react class based component.

The problem is that my state is an 2 dimensional array which looks like this:

this.state = {
  items: [
    {
      title: 'first depth',
      items: [
        {
          title: 'second depth',
        },
      ],
    },
  ],
};

For updating the first depth of the array inside my state object I use this code:

this.setState(({items}) => ({
  items: [
    ...items.slice(0, index),
    {
      ...items[index],
      title: 'new Title',
    },
    ...items.slice(index + 1),
  ],
}));

But I cannot update the second depth of the array inside my state.

Does someone has an idea how to update the second depth?

1
  • Hi, do you need to update all elements at once? if not you could just get the second deep item, update its content and then update the main array Commented Oct 2, 2020 at 8:18

4 Answers 4

2

create new state by spread, then change inner array by splice:

this.setState((oldState) => {
   const newState = {...oldState}; 
   const newItem = { ...newState.items[index],  title:"new Title"};
   newState.items.splice(index, 1,  newItem);
   return newState;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Following the same pattern, you will need the index of the 2nd depth item you want to change.

this.setState(({items}) => ({
  items: [
    ...items.slice(0, index),
    {
      items: [
        ...items[index].slice(0, indexOf2ndDepth),
        {
          title: 'new Title'
        },
        ...items[index].slice(indexOf2ndDepth + 1),
      ],
      title: 'new Title',
    },
    ...items.slice(index + 1),
  ],
};
}));

This can get pretty complex and I recommended you isolate the 2nd depth array first, make changes, and insert it into the 1st depth array


this.setState(({ items }) => {
  const secondDepthArray = [
    ...items[index].slice(0, indexOf2ndDepth),
    {
      title: 'new Title',
    },
    ...items[index].slice(indexOf2ndDepth + 1),
  ];

  return {
    items: [
      ...items.slice(0, index),
      {
        items: secondDepthArray
        title: 'new Title',
      },
      ...items.slice(index + 1),
    ],
  };
});

Comments

-1

To do that you can store your state in variable and update your array after that use prev prevState to update your State your array

Comments

-1

You can clone new array from state

const newItems = [...this.state.items]
// And then modify it

So if you want to update array just setState

this.setState({items: newItems})

1 Comment

Spread is a shallow clone, you need to clone each nested array also to answer the ops question.

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.