0

I'm just getting an eslint error about destructuring this code, but I have no idea how it should look. In this instance, I will probably just ignore this warning as this code is already pretty succinct, but, I am curious how it would be destructured. Any ideas or guidance is appreciated.

  _onChange = (e, key) => {
    const edited = { ...this.state[key] }; <--- this line is throwing the eslint error
    edited[e.name] = e.value;
    this.setState({
      [key]: edited,
    });
  };
Daltron
  • 1,729
  • 3
  • 20
  • 37
  • It is saying that `this.state[key]` is not defined? or can't be sure that it is an object? – Pedro Mutter Jan 09 '20 at 20:48
  • [`const { [key]: obj } = this.state;`](https://github.com/yannickcr/eslint-plugin-react/issues/1744) – Emile Bergeron Jan 09 '20 at 20:53
  • @James [`react/destructuring-assignment`](https://github.com/yannickcr/eslint-plugin-react/blob/5fac02c27d9b9d10a786c788f7b322009de04426/docs/rules/destructuring-assignment.md) – Emile Bergeron Jan 09 '20 at 20:54
  • Does this answer your question? [How to destructure into dynamically named variables in ES6?](https://stackoverflow.com/questions/35939289/how-to-destructure-into-dynamically-named-variables-in-es6) – Emile Bergeron Jan 09 '20 at 20:55
  • Oups, maybe wrong dupe target, this one is maybe more relevant: [How to destructure an object based on a dynamic defined variable](https://stackoverflow.com/q/54064859/1218980) – Emile Bergeron Jan 09 '20 at 20:56
  • @EmileBergeron Hey, I posted an answer, could you take a look and see if it's incorrect? – Daltron Jan 09 '20 at 21:41

1 Answers1

3

so, I was able to get there with the comments.

At the end of the day, I realized I just needed 'edited' to be an object containing the destructured object.

 _onChange = (e, key) => {
    const { [key]: { ...edited } } = this.state;
    edited[e.name] = e.value;
    this.setState({
      [key]: edited,
    });
  };

Here, edited will become { ...this.state[key] } which, after comparison, looks to be the same result as the previous code, but using the destructuring assignment.

I hope people will comment if they feel this is incorrect.

Even more simple, suggestion by Emile!

 _onChange = (e, key) => {
    const { [key]: current } = this.state;
    this.setState({
      [key]: { ...current, [e.name]: e.value },
    });
  };
Daltron
  • 1,729
  • 3
  • 20
  • 37