0

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

4
  • What are you expecting state to look like after the call to handleNameSubmit? Commented Mar 5, 2020 at 4:44
  • 1
    How does name get passed to handleNameSubmit? How is handleNameSubmit called? Also, not an answer to your question but you shouldn't use this.state in setState because updating of state can be deferred and create unexpected results, use "prevState". ie. this.setState((prevState, props) => ... Commented Mar 5, 2020 at 4:44
  • @ksav I expect an array of guest objects: [{name:guest 1}, {name:guest 2}] Commented Mar 5, 2020 at 12:02
  • @rshepp on button press in the form that takes text input for name. Commented Mar 5, 2020 at 12:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much Evgenii! Your description makes the distinction clear — I see why I had to pass an object with its field in the second case because the array started out empty without a data structure. When I tried the first case on fetched data that was already structured, it worked!
@Kat Happy to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.