Kalindu Prabash
Kalindu Prabash

Reputation: 25

React setState keeps running before variable is initialised

I have a function tied to a button click which updates the state. This src element in state is linked to an img component. However I have to click this button twice for the image to show up. I believe it's because setState is running before the setimg variable is fully loaded.

runThis(){
    var c = document.createElement("canvas")
    c.width = "450";
    c.height = "394"
    var ctx = c.getContext("2d")
    var newimg = document.createElement("img")
    newimg.src = this.props.location.url
    ctx.drawImage(newimg,10,10)
    var setimg = c.toDataURL("image/png")
    this.setState({
        src:setimg
    })
}

Upvotes: 0

Views: 192

Answers (2)

gautamits
gautamits

Reputation: 1292

You are setting state before image has finished loading. That might be causing problem. Apply onload event listener on image and setState when image has finished loading.

runThis(){
    var newimg = document.createElement("img")
    newimg.onload = this.imageLoaded
    newimg.src = this.props.location.url
}

imageLoaded(e){
    var c = document.createElement("canvas")
    c.width = "450";
    c.height = "394"
    var ctx = c.getContext("2d")
    ctx.drawImage(e.target,10,10)
    this.setState({
          src:c.toDataURL("image/png")
     })
}

Please let me know if it does not help.

Upvotes: 1

Hagai Harari
Hagai Harari

Reputation: 2877

You can shift setState into a callback function if the issue is indeed only it runs before context


   runThis({callback}){
      var c = document.createElement("canvas")
      c.width = "450";
      c.height = "394"
      var ctx = c.getContext("2d")
     var newimg = document.createElement("img")
     newimg.src = this.props.location.url
     ctx.drawImage(newimg,10,10)
     var setimg = c.toDataURL("image/png")
    callback(setimg)
    }

    //usage
    this.runThis({param=>this.setState({ src: param })})

Upvotes: 0

Related Questions