pattern_reducer.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. env_logger::init();
  10. dioxus::desktop::launch(app);
  11. }
  12. fn app(cx: Scope) -> Element {
  13. let state = use_state(&cx, PlayerState::new);
  14. cx.render(rsx!(
  15. div {
  16. h1 {"Select an option"}
  17. h3 { "The radio is... " [state.is_playing()], "!" }
  18. button { onclick: move |_| state.modify().reduce(PlayerAction::Pause),
  19. "Pause"
  20. }
  21. button { onclick: move |_| state.modify().reduce(PlayerAction::Play),
  22. "Play"
  23. }
  24. }
  25. ))
  26. }
  27. enum PlayerAction {
  28. Pause,
  29. Play,
  30. }
  31. #[derive(Clone)]
  32. struct PlayerState {
  33. is_playing: bool,
  34. }
  35. impl PlayerState {
  36. fn new() -> Self {
  37. Self { is_playing: false }
  38. }
  39. fn reduce(&mut self, action: PlayerAction) {
  40. match action {
  41. PlayerAction::Pause => self.is_playing = false,
  42. PlayerAction::Play => self.is_playing = true,
  43. }
  44. }
  45. fn is_playing(&self) -> &'static str {
  46. match self.is_playing {
  47. true => "currently playing!",
  48. false => "not currently playing",
  49. }
  50. }
  51. }