You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.8 KiB

4 years ago
  1. package com.example.playscalajsreact.component
  2. import com.example.playscalajsreact.model.MyGlobalState
  3. import japgolly.scalajs.react.vdom.VdomElement
  4. import japgolly.scalajs.react.Callback
  5. import japgolly.scalajs.react._
  6. import japgolly.scalajs.react.vdom.html_<^._
  7. import com.example.playscalajsreact.route.AppRouter
  8. import org.scalajs.dom
  9. import scala.scalajs.js
  10. import com.example.playscalajsreact.model.User
  11. import japgolly.scalajs.react.extra.StateSnapshot
  12. import com.softwaremill.quicklens._
  13. import monocle.macros.Lenses
  14. object Content {
  15. import scala.concurrent.ExecutionContext.Implicits.global
  16. final case class State(myGlobalState: MyGlobalState = MyGlobalState())
  17. final class Backend($ : BackendScope[_, State]) {
  18. val modifyState = modify[State](_.myGlobalState)
  19. val modifyUsername = modifyState andThenModify MyGlobalState.modifyUsername
  20. var interval: js.UndefOr[js.timers.SetIntervalHandle] =
  21. js.undefined
  22. def render(s: State): VdomElement =
  23. // MyGlobalState.ctx.provide(s.myGlobalState) {
  24. // <.div(AppRouter.router(AppRouter.Props(s.myGlobalState)))
  25. // }
  26. <.div
  27. val updateState = (s: State) => {
  28. val direct = $.withEffectsImpure
  29. direct.modState(modifyUsername.using(_ + "C"))
  30. }
  31. val refresh = (s: State) =>
  32. Callback {
  33. interval = js.timers.setInterval(1000) {
  34. updateState(s)
  35. }
  36. }
  37. val clear = Callback {
  38. interval foreach js.timers.clearInterval
  39. interval = js.undefined
  40. }
  41. }
  42. private val component = ScalaComponent
  43. .builder[Unit]("content")
  44. .initialState(State())
  45. .renderBackend[Backend]
  46. .componentDidMount($ => $.backend.refresh($.state))
  47. .componentWillUnmount(_.backend.clear)
  48. .build
  49. def apply() = component()
  50. }