1
0

timeout_count.rs 1008 B

12345678910111213141516171819202122232425262728293031
  1. // https://jakelazaroff.com/words/were-react-hooks-a-mistake/
  2. use dioxus::prelude::*;
  3. fn main() {
  4. dioxus_web::launch(app);
  5. }
  6. fn app(cx: Scope) -> Element {
  7. let count = use_ref(cx, || 0);
  8. let started = use_state(cx, || false);
  9. let start = move || {
  10. if !*started.get() {
  11. let count = count.clone(); // clone reference rather than value
  12. let alert = move || gloo_dialogs::alert(&format!("Your score was {}!", count.read()));
  13. gloo_timers::callback::Timeout::new(5_000, alert).forget();
  14. }
  15. started.set(true); // this cannot be done inside condition or infinite loop
  16. };
  17. cx.render(rsx! {
  18. button {
  19. onclick: move |_event| {
  20. start();
  21. *count.write() += 1;
  22. },
  23. // format is needed as {count} does not seemed to work in `if` within content
  24. if **started { format!("Current score: {}", count.write()) } else { "Start".to_string() }
  25. }
  26. })
  27. }