dioxus/examples/shared_state.rs

77 lines
1.5 KiB
Rust
Raw Normal View History

2023-07-02 20:41:00 +00:00
use std::collections::HashMap;
use dioxus::prelude::*;
fn main() {
dioxus_desktop::launch(App);
}
2023-07-02 20:41:00 +00:00
#[derive(Default)]
struct CoolData {
data: HashMap<usize, String>,
}
impl CoolData {
pub fn new(data: HashMap<usize, String>) -> Self {
Self { data }
}
pub fn view(&self, id: &usize) -> Option<&String> {
self.data.get(id)
}
pub fn set(&mut self, id: usize, data: String) {
self.data.insert(id, data);
}
}
#[component]
#[rustfmt::skip]
pub fn App(cx: Scope) -> Element {
2023-07-02 20:41:00 +00:00
use_shared_state_provider(cx, || CoolData::new(HashMap::from([
(0, "Hello, World!".to_string()),
(1, "Dioxus is amazing!".to_string())
])));
render!(
2023-07-02 20:41:00 +00:00
DataEditor {
id: 0
}
DataEditor {
id: 1
}
DataView {
id: 0
}
DataView {
id: 1
}
)
}
#[component]
2023-07-02 20:41:00 +00:00
fn DataEditor(cx: Scope, id: usize) -> Element {
let cool_data = use_shared_state::<CoolData>(cx).unwrap().read();
2023-07-14 23:34:49 +00:00
let my_data = &cool_data.view(id).unwrap();
2023-07-02 20:41:00 +00:00
render!(p {
"{my_data}"
2023-06-27 22:17:36 +00:00
})
}
#[component]
2023-07-02 20:41:00 +00:00
fn DataView(cx: Scope, id: usize) -> Element {
let cool_data = use_shared_state::<CoolData>(cx).unwrap();
2023-07-02 20:41:00 +00:00
let oninput = |e: FormEvent| cool_data.write().set(*id, e.value.clone());
2023-07-02 20:41:00 +00:00
let cool_data = cool_data.read();
2023-07-14 23:34:49 +00:00
let my_data = &cool_data.view(id).unwrap();
2023-07-02 20:41:00 +00:00
render!(input {
oninput: oninput,
value: "{my_data}"
})
}