callback.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. //! Example: RecoilCallback
  2. //! ------------------------
  3. //! This example shows how use_recoil_callback can be used to abstract over sets/gets.
  4. //! This hook provides a way to capture the RecoilApi object. In this case, we capture
  5. //! it in a closure an abstract the set/get functionality behind the update_title function.
  6. //!
  7. //! It should be straightforward to build a complex app with recoil_callback.
  8. use dioxus_core::prelude::*;
  9. use recoil::*;
  10. const TITLE: Atom<&str> = |_| "red";
  11. fn update_title(api: &RecoilApi) {
  12. match *api.get(&TITLE) {
  13. "green" => api.set(&TITLE, "yellow"),
  14. "yellow" => api.set(&TITLE, "red"),
  15. "red" => api.set(&TITLE, "green"),
  16. _ => {}
  17. }
  18. }
  19. static App: FC<()> = |cx| {
  20. let title = use_read(&cx, &TITLE);
  21. let next_light = use_recoil_api(&cx, |api| move |_| update_title(&api));
  22. rsx! { in cx,
  23. div {
  24. "{title}"
  25. button { onclick: {next_light}, "Next light" }
  26. }
  27. }
  28. };
  29. fn main() {
  30. wasm_bindgen_futures::spawn_local(dioxus_web::WebsysRenderer::start(App))
  31. }