scala.jsscalajs-react

ComponentDidMount actions with timeout


I am trying to perform some actions when my component did mount, but not immediately. My component looks like something this:

object MyComponent {
  def apply = compopnent()

  class Backend($: BackendScope) {
    def render = {
      // Some markup
    }

    def actions() = setTimeout(1000) {
      //... Some state modifications
    }
  }

  val component = ScalaComponent.builder[Unit]("My component")
  .renderBackend[Backend]
  .componentDidMount(f => f.backend.actions())  // HERE!
  .build
}

I get type missmatch. Found SetTimeoutHandle, required react.Callback.

How to use timeout inside componentDidMount?


Solution

  • CallbackTo class has async / delay / delayMs methods. You can get a delayed state mod callback like so: $.modState(...).delayMs(1000).void.


    Note that async callbacks in React.js need careful handling. 1 second from mounting, your component might already be unmounted (in theory), and if your callback runs when it's already unmounted you will get an error. I'm not sure if scalajs-react offers anything on top of React.js in that regard.