pattern_reducer.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. //!
  8. //! Currently we don't have a reducer pattern hook. If you'd like to add it,
  9. //! feel free to make a PR.
  10. use dioxus::prelude::*;
  11. fn main() {
  12. dioxus_desktop::launch(app);
  13. }
  14. fn app(cx: Scope) -> Element {
  15. let state = use_state(&cx, PlayerState::new);
  16. cx.render(rsx!(
  17. div {
  18. h1 {"Select an option"}
  19. h3 { "The radio is... " [state.is_playing()] "!" }
  20. button { onclick: move |_| state.make_mut().reduce(PlayerAction::Pause),
  21. "Pause"
  22. }
  23. button { onclick: move |_| state.make_mut().reduce(PlayerAction::Play),
  24. "Play"
  25. }
  26. }
  27. ))
  28. }
  29. enum PlayerAction {
  30. Pause,
  31. Play,
  32. }
  33. #[derive(Clone)]
  34. struct PlayerState {
  35. is_playing: bool,
  36. }
  37. impl PlayerState {
  38. fn new() -> Self {
  39. Self { is_playing: false }
  40. }
  41. fn reduce(&mut self, action: PlayerAction) {
  42. match action {
  43. PlayerAction::Pause => self.is_playing = false,
  44. PlayerAction::Play => self.is_playing = true,
  45. }
  46. }
  47. fn is_playing(&self) -> &'static str {
  48. match self.is_playing {
  49. true => "currently playing!",
  50. false => "not currently playing",
  51. }
  52. }
  53. }