2024-02-14 20:33:07 +00:00
|
|
|
//! Example: Global signals and memos
|
2024-01-19 19:46:17 +00:00
|
|
|
//!
|
2024-02-14 20:33:07 +00:00
|
|
|
//! This example demonstrates how to use global signals and memos to share state across your app.
|
|
|
|
//! Global signals are simply signals that live on the root of your app and are accessible from anywhere. To access a
|
|
|
|
//! global signal, simply use its methods like a regular signal. Calls to `read` and `write` will be forwarded to the
|
|
|
|
//! signal at the root of your app using the `static`'s address.
|
2024-01-19 19:46:17 +00:00
|
|
|
|
|
|
|
use dioxus::prelude::*;
|
|
|
|
|
2024-07-25 21:58:00 +00:00
|
|
|
const STYLE: &str = asset!("./examples/assets/counter.css");
|
2024-01-19 19:46:17 +00:00
|
|
|
|
2024-01-21 07:32:12 +00:00
|
|
|
static COUNT: GlobalSignal<i32> = Signal::global(|| 0);
|
2024-08-16 22:57:41 +00:00
|
|
|
static DOUBLED_COUNT: GlobalMemo<i32> = Memo::global(|| COUNT() * 2);
|
2024-01-21 07:32:12 +00:00
|
|
|
|
2024-07-23 17:29:37 +00:00
|
|
|
fn main() {
|
|
|
|
launch(app);
|
|
|
|
}
|
|
|
|
|
2024-01-19 19:46:17 +00:00
|
|
|
fn app() -> Element {
|
|
|
|
rsx! {
|
2024-07-25 21:58:00 +00:00
|
|
|
head::Link { rel: "stylesheet", href: STYLE }
|
2024-02-14 20:33:07 +00:00
|
|
|
Increment {}
|
|
|
|
Decrement {}
|
|
|
|
Reset {}
|
|
|
|
Display {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[component]
|
|
|
|
fn Increment() -> Element {
|
|
|
|
rsx! {
|
2024-01-19 19:46:17 +00:00
|
|
|
button { onclick: move |_| *COUNT.write() += 1, "Up high!" }
|
2024-02-14 20:33:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[component]
|
|
|
|
fn Decrement() -> Element {
|
|
|
|
rsx! {
|
2024-01-19 19:46:17 +00:00
|
|
|
button { onclick: move |_| *COUNT.write() -= 1, "Down low!" }
|
|
|
|
}
|
|
|
|
}
|
2024-02-14 20:33:07 +00:00
|
|
|
|
|
|
|
#[component]
|
|
|
|
fn Display() -> Element {
|
|
|
|
rsx! {
|
2024-07-03 00:09:57 +00:00
|
|
|
p { "Count: {COUNT}" }
|
|
|
|
p { "Doubled: {DOUBLED_COUNT}" }
|
2024-02-14 20:33:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[component]
|
|
|
|
fn Reset() -> Element {
|
2024-04-19 13:29:22 +00:00
|
|
|
// Not all write methods are available on global signals since `write` requires a mutable reference. In these cases,
|
2024-02-14 20:33:07 +00:00
|
|
|
// We can simply pull out the actual signal using the signal() method.
|
2024-08-16 22:57:41 +00:00
|
|
|
let mut as_signal = use_hook(|| COUNT.resolve());
|
2024-02-14 20:33:07 +00:00
|
|
|
|
|
|
|
rsx! {
|
|
|
|
button { onclick: move |_| as_signal.set(0), "Reset" }
|
|
|
|
}
|
|
|
|
}
|