future.rs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. //! A simple example that shows how to use the use_future hook to run a background task.
  2. //!
  3. //! use_future won't return a value, analogous to use_effect.
  4. //! If you want to return a value from a future, use use_resource instead.
  5. use async_std::task::sleep;
  6. use dioxus::prelude::*;
  7. fn main() {
  8. dioxus::launch(app);
  9. }
  10. fn app() -> Element {
  11. let mut count = use_signal(|| 0);
  12. // use_future is a non-reactive hook that simply runs a future in the background.
  13. // You can use the UseFuture handle to pause, resume, restart, or cancel the future.
  14. use_future(move || async move {
  15. loop {
  16. sleep(std::time::Duration::from_millis(200)).await;
  17. count += 1;
  18. }
  19. });
  20. // use_effect is a reactive hook that runs a future when signals captured by its reactive context
  21. // are modified. This is similar to use_effect in React and is useful for running side effects
  22. // that depend on the state of your component.
  23. //
  24. // Generally, we recommend performing async work in event as a reaction to a user event.
  25. use_effect(move || {
  26. spawn(async move {
  27. sleep(std::time::Duration::from_secs(5)).await;
  28. count.set(100);
  29. });
  30. });
  31. // You can run futures directly from event handlers as well. Note that if the event handler is
  32. // fired multiple times, the future will be spawned multiple times.
  33. rsx! {
  34. h1 { "Current count: {count}" }
  35. button {
  36. onclick: move |_| async move {
  37. sleep(std::time::Duration::from_millis(200)).await;
  38. count.set(0);
  39. },
  40. "Slowly reset the count"
  41. }
  42. }
  43. }