0

I have code that passes data through a react component from a form to a backend. The backend processes it and sends a response. However I am confused with the const keyword, I am seeing in the code.

axios{
  .post('/api/users/register', newUser)
  .then(res => console.log(res.data))
  .catch(err => this.setState({ errors: err.response.data }));

}

render() {
    const { errors } = this.state;
     <div className="form-group">
              <input
                type="text"
                className={classnames('form-control form-control-lg', {
                  'is-invalid': errors.name
                })}
                placeholder="Name"
                name="name"
                value={this.state.name}
                onChange={this.onChange}
      />

You can assume that the code works. However, why is const {errors} defined like this, and how come it can access the errors list from the backend is-invalid': errors.name.

Thank you.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
Shadman Mahmood
  • 133
  • 1
  • 3
  • 15
  • It's ES6 destructing: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment. Basically `const { errors } = this.state` is the same as `this.state.errors`. For example, in the `input` you have `value={this.state.value}`. That can also be destructed as `const { value } = this.state`, then `value={value}`. The above error simply states that `errors` doesn't have a property `name`. Try `console.log(error)` to see how `errors` is structured. – Matt Carlotta Sep 30 '18 at 13:30
  • Oops. Second to last sentence is incorrect. Basically when `errors` is being set to state, it's an `object` with properties. In this case, it has a `name` property. However, you can destructure that as well: `const { errors: {name} } = this.state`. Now the variable `name` is shorthand for `this.state.errors.name`. – Matt Carlotta Sep 30 '18 at 13:38

1 Answers1

0

This is called object destructuring. const {errors} = this.state; is a cleaner way of accessing the errors key in your local state than typing this.state.errors everywhere. So now when you need to use errors you can just pass it in somewhere like this

const {errors} = this.state;

<YourComponent
  errors={errors}
/>
jman93
  • 367
  • 3
  • 9
  • "*typing this.state.errors everywhere*" - given that it is used exactly once, it's not really "cleaner" in this specific example – Bergi Sep 30 '18 at 15:14
  • No but if you had a good amount of components using a specific property in either the local state or the passed props. It might make sense to use object destructuring to shorten up the code a little – jman93 Oct 01 '18 at 01:55