Mike
Mike

Reputation: 12819

Preferred ES6 arrow function syntax formatting

I have an onChange event handler that is shaping up like this:

(e) => (value => this.setState(prevState => ({
        form: {
            ...prevState.form,
            email: value
        }
    })))(e.target.value)

I minified it down to that from this

(e) => {
    let value = e.target.value;
    this.setState((prevState) => ({
        form: {
            ...prevState.form,
            password: value
        }
    }))
}

Neither of these are very appealing. I like the first one b/c it is 3 less lines of code but it also has a ton of parenthesis. Is there another variation I might be missing that can clean this up further? The use of the spread operator adds an extra paren, could this be removed somehow?

Thanks

Upvotes: 1

Views: 88

Answers (3)

Tholle
Tholle

Reputation: 112787

You could destructure out the value from the event and just do the setState as the only statement.

({ target: { value } }) => this.setState(prevState => ({
  form: {
    ...prevState.form,
    password: value
  }
}));

Upvotes: 3

Jee Mok
Jee Mok

Reputation: 6556

Just another idea for you :)

event => {
   const password = event.target.value;
   const form = { ...this.state.form, password };
   this.setState({ form });
}

Upvotes: 1

Jackson
Jackson

Reputation: 3518

Personally I would use this:

e => {
    let value = e.target.value;
    this.setState({
        form: {
            ...this.state.form,
            password: value
        }
    });
}

Upvotes: 1

Related Questions