0
addTOList= (id) =>{
  const movieId = id
  const movie = movies.find( ({ id }) => id === movieId );
  const stateMovie = [...this.state.movie, movie]
  console.log(stateMovie)
  this.setState({
    movie : stateMovie
  })
  console.log(this.state.movie)
  localStorage.setItem('movies', JSON.stringify(this.state.movie))
  this.state.movie.map(mov =>{
  })
}

This function will be triggered when the (Add to list) button is clicked. but I have to click twice to change the state.` sorry for horrible English

Stuck
  • 11,225
  • 11
  • 59
  • 104

3 Answers3

0

react state changes are synchronous.

Check this question & answer here

Kid
  • 1,160
  • 2
  • 14
  • 31
0

If your 'next state' depends on the 'previous state' then you should use this pattern:

  this.setState(prev => ({
    ...prev,
    movie : [...prev.movie, movie],
  }))

Also you must wait until the state change has been applied by react before you will see the changes in your console statement.

Stuck
  • 11,225
  • 11
  • 59
  • 104
0

setState is an async function, it do not setstate in async manner but later, you can use a callback function, if you want to run a code snippet after set state is run:

addTOList = () => { this.setState({ movie : stateMovie }, () => { console.log(this.state.movie) }) }

Manoj
  • 2,059
  • 3
  • 12
  • 24