global.rs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //! Example: Global signals and memos
  2. //!
  3. //! This example demonstrates how to use global signals and memos to share state across your app.
  4. //! Global signals are simply signals that live on the root of your app and are accessible from anywhere. To access a
  5. //! global signal, simply use its methods like a regular signal. Calls to `read` and `write` will be forwarded to the
  6. //! signal at the root of your app using the `static`'s address.
  7. use dioxus::prelude::*;
  8. const STYLE: Asset = asset!("/examples/assets/counter.css");
  9. static COUNT: GlobalSignal<i32> = Signal::global(|| 0);
  10. static DOUBLED_COUNT: GlobalMemo<i32> = Memo::global(|| COUNT() * 2);
  11. fn main() {
  12. dioxus::launch(app);
  13. }
  14. fn app() -> Element {
  15. rsx! {
  16. document::Link { rel: "stylesheet", href: STYLE }
  17. Increment {}
  18. Decrement {}
  19. Reset {}
  20. Display {}
  21. }
  22. }
  23. #[component]
  24. fn Increment() -> Element {
  25. rsx! {
  26. button { onclick: move |_| *COUNT.write() += 1, "Up high!" }
  27. }
  28. }
  29. #[component]
  30. fn Decrement() -> Element {
  31. rsx! {
  32. button { onclick: move |_| *COUNT.write() -= 1, "Down low!" }
  33. }
  34. }
  35. #[component]
  36. fn Display() -> Element {
  37. rsx! {
  38. p { "Count: {COUNT}" }
  39. p { "Doubled: {DOUBLED_COUNT}" }
  40. }
  41. }
  42. #[component]
  43. fn Reset() -> Element {
  44. // Not all write methods are available on global signals since `write` requires a mutable reference. In these cases,
  45. // We can simply pull out the actual signal using the signal() method.
  46. let mut as_signal = use_hook(|| COUNT.resolve());
  47. rsx! {
  48. button { onclick: move |_| as_signal.set(0), "Reset" }
  49. }
  50. }