AJSwift
AJSwift

Reputation: 719

setState using spread operator on currentState object

I am trying to make sense of the following syntax:

this.setState(currState => ({
      ...currState,
      user: {
        ...currState.user,
        [name]: value,
      },
    }));

I know the setState will update the state of this component by affecting the current state of the component, in this case, merging the currentState and user object each into a new state. Does this mean when I add a new user A and then add a second user B, the state object will have both A and B object as the new state i.e. two user objects?

class AddUser extends Component {
  state = {
    user: {
      firstName: '',
      lastName: '',
      username: '',
    },
    userExists: false,
  };
  contactExists = currUsername => {};

  handleSubmit = event => {};

  handleInputChange = event => {
    const { name, value } = event.target;
    this.setState(currState => ({
      ...currState,
      user: {
        ...currState.user,
        [name]: value,
      },
    }));
  };
  isDisabled = () => {};

  render() {
    const { firstName, lastName, username } = this.state.user;

    return (
      <div>
        <h1>New User</h1>
        <form onSubmit={this.handleSubmit}>
          <div>
            <input
              type="text"
              name="firstName"
              placeholder="Enter First Name"
              value={firstName}
              onChange={this.handleInputChange}
            />
            <input
              type="text"
              name="lastName"
              placeholder="Enter Last Name"
              value={lastName}
              onChange={this.handleInputChange}
            />
            <input
              type="text"
              name="username"
              placeholder="Enter username"
              value={username}
              onChange={this.handleInputChange}
            />
          </div>
          <button disabled={this.isDisabled()}>Add</button>
        </form>
        {this.state.userExists ? (
          <p className="error">You cannot add a user that already exists.</p>
        ) : (
          ''
        )}
      </div>
    );
  }
} 

Upvotes: 0

Views: 136

Answers (1)

ray
ray

Reputation: 27275

This updates state.user to reflect the change to the input that triggered the event, using the input’s name as the property/key and the input’s value as its value, while retaining the other values.

The bracket syntax [name] is a computed property, so if the input’s name is “banana” this is the equivalent of setting { banana: value }.

Upvotes: 1

Related Questions