1
0

shared_state.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. use std::collections::HashMap;
  2. use dioxus::prelude::*;
  3. fn main() {
  4. dioxus_desktop::launch(App);
  5. }
  6. #[derive(Default)]
  7. struct CoolData {
  8. data: HashMap<usize, String>,
  9. }
  10. impl CoolData {
  11. pub fn new(data: HashMap<usize, String>) -> Self {
  12. Self { data }
  13. }
  14. pub fn view(&self, id: &usize) -> Option<&String> {
  15. self.data.get(id)
  16. }
  17. pub fn set(&mut self, id: usize, data: String) {
  18. self.data.insert(id, data);
  19. }
  20. }
  21. #[component]
  22. #[rustfmt::skip]
  23. pub fn App() -> Element {
  24. use_shared_state_provider(|| CoolData::new(HashMap::from([
  25. (0, "Hello, World!".to_string()),
  26. (1, "Dioxus is amazing!".to_string())
  27. ])));
  28. render!(
  29. DataEditor {
  30. id: 0
  31. }
  32. DataEditor {
  33. id: 1
  34. }
  35. DataView {
  36. id: 0
  37. }
  38. DataView {
  39. id: 1
  40. }
  41. )
  42. }
  43. #[component]
  44. fn DataEditor(id: usize) -> Element {
  45. let data = use_shared_state::<CoolData>()?;
  46. render! {
  47. p {
  48. {data.read().view(id)?}
  49. }
  50. }
  51. }
  52. #[component]
  53. fn DataView(id: usize) -> Element {
  54. let data = use_shared_state::<CoolData>()?;
  55. render! {
  56. input {
  57. oninput: move |e: FormEvent| data.write().set(*id, e.value()),
  58. value: data.read().view(id)?
  59. }
  60. }
  61. }