reducer.rs 1.5 KB

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