2021-06-24 02:32:54 +00:00
|
|
|
//! Example: Reducer Pattern
|
|
|
|
//! -----------------
|
2021-07-09 16:47:41 +00:00
|
|
|
//!
|
2021-10-24 17:30:36 +00:00
|
|
|
//! This example shows how to encapsulate state in dioxus components with the reducer pattern.
|
2021-06-24 02:32:54 +00:00
|
|
|
//! This pattern is very useful when a single component can handle many types of input that can
|
|
|
|
//! be represented by an enum.
|
|
|
|
|
|
|
|
use dioxus::prelude::*;
|
2022-01-03 05:42:17 +00:00
|
|
|
|
2021-07-08 13:29:12 +00:00
|
|
|
fn main() {
|
2024-01-20 08:11:55 +00:00
|
|
|
launch(app);
|
2021-07-08 13:29:12 +00:00
|
|
|
}
|
2021-06-24 02:32:54 +00:00
|
|
|
|
2024-01-14 04:51:37 +00:00
|
|
|
fn app() -> Element {
|
2024-01-16 07:24:59 +00:00
|
|
|
let mut state = use_signal(|| PlayerState { is_playing: false });
|
2021-06-24 02:32:54 +00:00
|
|
|
|
2024-01-16 19:18:46 +00:00
|
|
|
rsx!(
|
2024-02-14 21:48:58 +00:00
|
|
|
style { {include_str!("./assets/radio.css")} }
|
|
|
|
h1 {"Select an option"}
|
|
|
|
|
|
|
|
// Add some cute animations if the radio is playing!
|
|
|
|
div { class: if state.read().is_playing { "bounce" },
|
|
|
|
"The radio is... ", {state.read().is_playing()}, "!"
|
2021-06-24 02:32:54 +00:00
|
|
|
}
|
2024-02-14 21:48:58 +00:00
|
|
|
|
|
|
|
button { id: "play", onclick: move |_| state.write().reduce(PlayerAction::Pause), "Pause" }
|
|
|
|
button { id: "pause", onclick: move |_| state.write().reduce(PlayerAction::Play), "Play" }
|
2024-01-14 05:12:21 +00:00
|
|
|
)
|
2022-01-02 23:35:38 +00:00
|
|
|
}
|
2021-06-24 02:32:54 +00:00
|
|
|
|
|
|
|
enum PlayerAction {
|
|
|
|
Pause,
|
|
|
|
Play,
|
|
|
|
}
|
|
|
|
|
2021-07-09 16:47:41 +00:00
|
|
|
#[derive(Clone)]
|
2021-06-24 02:32:54 +00:00
|
|
|
struct PlayerState {
|
|
|
|
is_playing: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PlayerState {
|
|
|
|
fn reduce(&mut self, action: PlayerAction) {
|
|
|
|
match action {
|
|
|
|
PlayerAction::Pause => self.is_playing = false,
|
|
|
|
PlayerAction::Play => self.is_playing = true,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fn is_playing(&self) -> &'static str {
|
|
|
|
match self.is_playing {
|
|
|
|
true => "currently playing!",
|
|
|
|
false => "not currently playing",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|