reducer.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //! Example: Reducer Pattern
  2. //! -----------------
  3. //!
  4. //! This example shows how to encapsulate sate 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. dioxus::desktop::launch(App, |c| c);
  10. }
  11. pub static App: FC<()> = |cx| {
  12. let state = use_state(cx, PlayerState::new);
  13. let is_playing = state.is_playing();
  14. cx.render(rsx! {
  15. div {
  16. h1 {"Select an option"}
  17. h3 {"The radio is... {is_playing}!"}
  18. button {
  19. "Pause"
  20. onclick: move |_| state.get_mut().reduce(PlayerAction::Pause)
  21. }
  22. button {
  23. "Play"
  24. onclick: move |_| state.get_mut().reduce(PlayerAction::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. }