pattern_reducer.rs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. launch_desktop(app);
  10. }
  11. fn app() -> Element {
  12. let mut state = use_signal(|| PlayerState { is_playing: false });
  13. rsx!(
  14. div {
  15. h1 {"Select an option"}
  16. h3 { "The radio is... ", {state.read().is_playing()}, "!" }
  17. button { onclick: move |_| state.write().reduce(PlayerAction::Pause), "Pause" }
  18. button { onclick: move |_| state.write().reduce(PlayerAction::Play), "Play" }
  19. }
  20. )
  21. }
  22. enum PlayerAction {
  23. Pause,
  24. Play,
  25. }
  26. #[derive(Clone)]
  27. struct PlayerState {
  28. is_playing: bool,
  29. }
  30. impl PlayerState {
  31. fn reduce(&mut self, action: PlayerAction) {
  32. match action {
  33. PlayerAction::Pause => self.is_playing = false,
  34. PlayerAction::Play => self.is_playing = true,
  35. }
  36. }
  37. fn is_playing(&self) -> &'static str {
  38. match self.is_playing {
  39. true => "currently playing!",
  40. false => "not currently playing",
  41. }
  42. }
  43. }