0

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 })
1
  • 2
    As a side note, the argument to setState() should be an object. The argument you tried isn't a valid Javascript object, you need square brackets if you want to use variables as the key name: this.setState({ [some.nested.object.value]: 5 }) Commented Apr 10, 2019 at 23:17

2 Answers 2

1

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,
      },
    },
  },
}));
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.