reducer.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //! Example: Reducer Pattern
  2. //! -----------------
  3. //!
  4. //! This example shows how to encapsulate state in dioxus components with the reducer pattern.
  5. //! This pattern is very useful when a single component can handle many types of input that can
  6. //! be represented by an enum.
  7. use dioxus::prelude::*;
  8. fn main() {
  9. launch(app);
  10. }
  11. fn app() -> Element {
  12. let mut state = use_signal(|| PlayerState { is_playing: false });
  13. rsx!(
  14. style { {include_str!("./assets/radio.css")} }
  15. h1 {"Select an option"}
  16. // Add some cute animations if the radio is playing!
  17. div { class: if state.read().is_playing { "bounce" },
  18. "The radio is... " {state.read().is_playing()} "!"
  19. }
  20. button { id: "play", onclick: move |_| state.write().reduce(PlayerAction::Pause), "Pause" }
  21. button { id: "pause", onclick: move |_| state.write().reduce(PlayerAction::Play), "Play" }
  22. )
  23. }
  24. enum PlayerAction {
  25. Pause,
  26. Play,
  27. }
  28. #[derive(Clone)]
  29. struct PlayerState {
  30. is_playing: bool,
  31. }
  32. impl PlayerState {
  33. fn reduce(&mut self, action: PlayerAction) {
  34. match action {
  35. PlayerAction::Pause => self.is_playing = false,
  36. PlayerAction::Play => self.is_playing = true,
  37. }
  38. }
  39. fn is_playing(&self) -> &'static str {
  40. match self.is_playing {
  41. true => "currently playing!",
  42. false => "not currently playing",
  43. }
  44. }
  45. }