reducer.rs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //! Example: Reducer Pattern
  2. //! -----------------
  3. //! This example shows how to encapsulate sate in dioxus components with the reducer pattern.
  4. //! This pattern is very useful when a single component can handle many types of input that can
  5. //! be represented by an enum.
  6. fn main() {}
  7. use dioxus::prelude::*;
  8. pub static ExampleReducer: FC<()> = |ctx| {
  9. let (state, reduce) = use_reducer(&ctx, PlayerState::new, PlayerState::reduce);
  10. let is_playing = state.is_playing();
  11. ctx.render(rsx! {
  12. div {
  13. h1 {"Select an option"}
  14. h3 {"The radio is... {is_playing}!"}
  15. button {
  16. "Pause"
  17. onclick: move |_| reduce(PlayerAction::Pause)
  18. }
  19. button {
  20. "Play"
  21. onclick: move |_| reduce(PlayerAction::Play)
  22. }
  23. }
  24. })
  25. };
  26. enum PlayerAction {
  27. Pause,
  28. Play,
  29. }
  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. }