pattern_reducer.rs 1.4 KB

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