1

I really need your help! I've written two versions of react functions. One with the spread operator and the other without and only the version without is working.

Working version:

onAddBook() {
  var updatedBooks = this.state.books;
  var finalBook = {
    title: this.state.title
  };
  updatedBooks.push(finalBooks);
  this.setState({
    books: updatedBooks
  });
}

Not working:

var finalBook = {
  title: this.state.title
}
this.setState({
  books: [...this.state.books, finalBook]
});
Tholle
  • 108,070
  • 19
  • 198
  • 189
Eva Cohen
  • 485
  • 1
  • 9
  • 24
  • Welcome to stackoverflow Eva! It's hard to say what might be wrong from this code alone. Could you include your entire component? – Tholle Jul 04 '18 at 19:04
  • Yes sorry. The error I received: cannot read property title of undefined. Im not home as soon as i get home i will add the entire component thanks (: – Eva Cohen Jul 04 '18 at 19:08
  • That error doesn't seem related to your use of the spread operator. Your spread version looks correct. – Tholle Jul 04 '18 at 19:09
  • @EvaCohen Please, provide https://stackoverflow.com/help/mcve , this is a requirement for code-related questions. Where exactly do you have 'Not working' code? The error clearly states that there's no `this.state` where you use it. There's no problem with spread, as it was already mentioned. – Estus Flask Jul 04 '18 at 19:46

1 Answers1

0

As everyone mentioned in the question there is nothing wrong with your spread implementation. Please find the added snippet for that confirmation.

Primary Check Check whether your transpiler supports ES6 with React. If not; try looking in adding one for your project like babel. Check this discussion for more info

Secondary Check Referring to your error cannot read property title of undefined could be something related to your this.state.title in the code. Either the title is undefined in your state or not yet initialised by the time this.state.title is called. So please look into the exact line of code where it is breaking to trace the error.

// Without the spread operator
const updatedBooks = [{ title: 'Hi' }, { title: 'Hello' }]
const finalBook = {
  title: 'How'
}
updatedBooks.push(finalBook)
console.log('result without spread:', updatedBooks)


// With Spread operator
const books = [{ title: 'Hi' }, { title: 'Hello' }]
const finalBook2 = {
  title: 'How'
}
console.log('result with spread',[...books, finalBook2])
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
bh4r4th
  • 3,760
  • 1
  • 21
  • 25