pattern_reducer.rs 1.4 KB

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