How can I update a nested state with arrays in React?

I have a nested array, and I am trying to update some properties, but i don't know the syntax in react to do that.

this.state = {
databasesList: {
        name: 'Databases',
        toggled: true,
        children: [
          {
            name: 'OneDatabase',
            children: [
              { name: 'collection1' },
              { name: 'collection2' }
            ]
          }
        ]
      }
}

I am trying to update with this, but it does not work:

this.setState({ this.state.databasesList.children[0].children: newData })

Upvotes: 0

Views: 72

Answers (2)

stwilz
stwilz

Reputation: 2397

If you want to use lodash set here's a pretty nifty solution. https://twitter.com/stwilz/status/1092958989208317952

But if you just want to use set on it's own this would be the way to go.

    const yourFunction = newData => this.setState(state => set(state, ['databasesList', 'children', 0, 'children'], newData));

The spread operator works fine as well. It just gets super verbose when you have a huge state object.

Upvotes: 0

viciousP
viciousP

Reputation: 520

To set nested state in React you should use JS spread operator so in your example it should be something like this:

this.setState((prevState) => ({
  ...prevState,
  databasesList: {
    ...prevState.databasesList,
    children: {
      ...prevState.databasesList.children[0],
      children: {
        newData,
      },
    },
  },
}));

Upvotes: 1

Related Questions