1
0

api_mvc.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //! RecoilAPI Pattern
  2. //! ----------------
  3. //! This example demonstrates how the use_recoil_callback hook can be used to build view controllers.
  4. //! These view controllers are cheap to make and can be easily shared across the app to provide global
  5. //! state logic to many components.
  6. //!
  7. //! This pattern is meant to replace the typical use_dispatch pattern used in Redux apps.
  8. use dioxus_core::prelude::*;
  9. use recoil::*;
  10. const TITLE: Atom<String> = |_| format!("Heading");
  11. const SUBTITLE: Atom<String> = |_| format!("Subheading");
  12. struct TitleController(RecoilApi);
  13. impl TitleController {
  14. fn new(api: RecoilApi) -> Self {
  15. Self(api)
  16. }
  17. fn uppercase(&self) {
  18. self.0.modify(&TITLE, |f| *f = f.to_uppercase());
  19. self.0.modify(&SUBTITLE, |f| *f = f.to_uppercase());
  20. }
  21. fn lowercase(&self) {
  22. self.0.modify(&TITLE, |f| *f = f.to_lowercase());
  23. self.0.modify(&SUBTITLE, |f| *f = f.to_lowercase());
  24. }
  25. }
  26. fn main() {
  27. wasm_bindgen_futures::spawn_local(dioxus_web::WebsysRenderer::start(|cx| {
  28. let title = use_read(&cx, &TITLE);
  29. let subtitle = use_read(&cx, &SUBTITLE);
  30. let controller = TitleController::new(use_recoil_api(&cx));
  31. rsx! { in cx,
  32. div {
  33. "{title}"
  34. "{subtitle}"
  35. button { onclick: move |_| controller.uppercase(), "Uppercase" }
  36. button { onclick: move |_| controller.lowercase(), "Lowercase" }
  37. }
  38. }
  39. }))
  40. }