Kat
Kat

Reputation: 105

React native setState updates array with empty object

I have a class constructed as follows -:

  constructor(props) {
    super(props);
    this.state = {
      name: '',
      guestsStore:[],
    };
  }

And I have a form that takes a text input and that is supposed to add the submitted name to the guestsStore array by calling this.handleNameSubmit

The following code doesn't work even if I have seen it in multiple code examples. It updates state but with an empty object-:

  handleNameSubmit = (name) => {
    this.setState({
      guestsStore: [...this.state.guestsStore, name],
    });
  };

The following code works and updates state with the name.

handleNameSubmit = (name) => {
    this.setState({
    guestsStore:[...this.state.guestsStore, {name:this.state.name}],
    })
  }

I am new to React Native and would like to understand why this happens. Why in this case does the first code example fail even if it works in so many other cases

Upvotes: 0

Views: 709

Answers (1)

Evgenii Klepilin
Evgenii Klepilin

Reputation: 695

These two approaches accomplish different things.

 handleNameSubmit = (name) => {
     this.setState({
         guestsStore: [...this.state.guestsStore, name],
     });
 };

This code adds field name: name to the expanded array this.state.guestsStore, and then assembles the array into guestsStore of the new state.

handleNameSubmit = (name) => {
    this.setState({
        guestsStore:[...this.state.guestsStore, {name:this.state.name}],
    })
}

This code adds object {name: this.state.name} with a field to the expanded array this.state.guestsStore and then assembles it into guestsStore field of a new state.

You need to make sure you understand the difference between the two and use the one that you need in your case.

Upvotes: 1

Related Questions