Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Last active July 17, 2017 17:11
Show Gist options
  • Save coryhouse/9bd989ec8f89e3fcf058129b67a509ad to your computer and use it in GitHub Desktop.
Save coryhouse/9bd989ec8f89e3fcf058129b67a509ad to your computer and use it in GitHub Desktop.
Consise example of object spread in React
updateState({target}) {
this.setState({user: {...this.state.user, [target.name]: target.value}});
}
@donavon
Copy link

donavon commented Jun 12, 2017

There's a fine line between streamline code and writing something that's too terse. For readability/maintainability I prefer my initial suggestion. I know that it's not always avoidable, but it's a red flag for me to see thingie.something when reviewing code.

updateState({ target }) {
  const { name, value } = target;
  const user = { ...this.state.user, [name]: value };
  this.setState({ user });
}

If you absolutely must go more concise, I'd rather see you destructure target into name and value directly in the passed parameters:

updateState({ target: { name, value } }) {
  const user = { ...this.state.user, [name]: value };
  this.setState({ user });
}

Maybe then your one liner would't seem so bad. ;)

updateState({ target: { name, value } }) {
  this.setState({ user: { ...this.state.user, [name]: value } });
}

@coryhouse
Copy link
Author

@donavon Good stuff. I can see your point, but doesn't this.state.user break your rule then?

I'd welcome your input on a related blog post that I'm about to publish: https://medium.com/@housecor/handling-state-in-react-d1f5c00249d5

@donavon
Copy link

donavon commented Jun 14, 2017

but doesn't this.state.user break your rule then?

Yes it does, which is why I added "I know that it's not always avoidable". 'name and value are no brainers, getting the current user from state is less so. I'm always struggling with my devs to write Clean Code, but know "when to say when". I think the right answer is somewhere on this page, but I'm not sure which one it is. ;)

I'd be happy to take a look and give you my feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment