patrickhuang94
patrickhuang94

Reputation: 2115

setState not updating in function call

I've read many posts concerning this issue, something about this.setState being an asynchronous call, so it doesn't re-render every time. How do I approach this problem given the following context:

getInitialState: () ->
    return {
        page: ""
    }

choose: (event) ->
    console.log(@props.id) # This is the correct id that I want to pass into state
    @setState({
        page: @props.id # @state.page isn't being set to @props.id 
    })

render: () ->
    return (
        <button onClick={@choose}>Click me</button>
    )

I've tried to bind the onClick call like onClick={@choose.bind(@)} but it seems that React already does this automatically. How do I properly set the state in choose() after I click on the button?

SOLUTION: this is the child component which is calling a parent component, so the state got lost somewhere in there. All I had to do was to call pass down the id from the parent component as props and access it through there.

Upvotes: 0

Views: 556

Answers (1)

cyberskunk
cyberskunk

Reputation: 1772

Your code seems correct. setState is not guaranteed to be synchronous, its execution might be delayed. It means that if you try to access @state.name right after @setState in your code, you gonna get old value

choose: (event) ->
  console.log(@props.id) # This is the correct id that I want to pass into state
  @setState({
     page: @props.id # @state.page isn't being set to @props.id 
  })
  console.log(@state.name) # here's old value

So you should use second parameter of the @setState, which is callback function which will be called right after updating state, so

choose: (event) ->
  console.log(@props.id) # This is the correct id that I want to pass into state
  @setState({
     page: @props.id # @state.page isn't being set to @props.id 
  }, () => 
      console.log(@state.name) # <-- updated value here!
  )
  console.log(@state.name) # here's old value

Upvotes: 3

Related Questions