Daltron
Daltron

Reputation: 1866

How to properly destructure assignment with dynamic key? (react/destructuring-assignment)

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,
    });
  };

Upvotes: 0

Views: 960

Answers (1)

Daltron
Daltron

Reputation: 1866

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 },
    });
  };

Upvotes: 3

Related Questions