reducer.rs 1.5 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. use dioxus::prelude::*;
  8. const STYLE: Asset = asset!("/examples/assets/radio.css");
  9. fn main() {
  10. dioxus::launch(app);
  11. }
  12. fn app() -> Element {
  13. let mut state = use_signal(|| PlayerState { is_playing: false });
  14. rsx!(
  15. document::Link { rel: "stylesheet", href: STYLE }
  16. h1 {"Select an option"}
  17. // Add some cute animations if the radio is playing!
  18. div { class: if state.read().is_playing { "bounce" },
  19. "The radio is... " {state.read().is_playing()} "!"
  20. }
  21. button { id: "play", onclick: move |_| state.write().reduce(PlayerAction::Pause), "Pause" }
  22. button { id: "pause", onclick: move |_| state.write().reduce(PlayerAction::Play), "Play" }
  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 reduce(&mut self, action: PlayerAction) {
  35. match action {
  36. PlayerAction::Pause => self.is_playing = false,
  37. PlayerAction::Play => self.is_playing = true,
  38. }
  39. }
  40. fn is_playing(&self) -> &'static str {
  41. match self.is_playing {
  42. true => "currently playing!",
  43. false => "not currently playing",
  44. }
  45. }
  46. }