global.rs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. fn main() {
  9. launch(app);
  10. }
  11. static COUNT: GlobalSignal<i32> = Signal::global(|| 0);
  12. static DOUBLED_COUNT: GlobalMemo<i32> = Signal::global_memo(|| COUNT() * 2);
  13. fn app() -> Element {
  14. rsx! {
  15. style { {include_str!("./assets/counter.css")} }
  16. Increment {}
  17. Decrement {}
  18. Reset {}
  19. Display {}
  20. }
  21. }
  22. #[component]
  23. fn Increment() -> Element {
  24. rsx! {
  25. button { onclick: move |_| *COUNT.write() += 1, "Up high!" }
  26. }
  27. }
  28. #[component]
  29. fn Decrement() -> Element {
  30. rsx! {
  31. button { onclick: move |_| *COUNT.write() -= 1, "Down low!" }
  32. }
  33. }
  34. #[component]
  35. fn Display() -> Element {
  36. rsx! {
  37. p { "Count: {COUNT}" }
  38. p { "Doubled: {DOUBLED_COUNT}" }
  39. }
  40. }
  41. #[component]
  42. fn Reset() -> Element {
  43. // Not all write methods are available on global signals since `write` requires a mutable reference. In these cases,
  44. // We can simply pull out the actual signal using the signal() method.
  45. let mut as_signal = use_hook(|| COUNT.signal());
  46. rsx! {
  47. button { onclick: move |_| as_signal.set(0), "Reset" }
  48. }
  49. }