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::*;
|
2021-07-08 13:29:12 +00:00
|
|
|
fn main() {
|
2021-07-26 16:14:48 +00:00
|
|
|
env_logger::init();
|
2021-12-15 20:56:53 +00:00
|
|
|
dioxus::desktop::launch(App);
|
2021-07-08 13:29:12 +00:00
|
|
|
}
|
2021-06-24 02:32:54 +00:00
|
|
|
|
2021-12-29 04:48:25 +00:00
|
|
|
pub static App: Component = |cx| {
|
2021-12-15 20:56:53 +00:00
|
|
|
let state = use_state(&cx, PlayerState::new);
|
2021-06-24 02:32:54 +00:00
|
|
|
|
|
|
|
let is_playing = state.is_playing();
|
|
|
|
|
2021-09-24 06:10:54 +00:00
|
|
|
rsx!(cx, div {
|
|
|
|
h1 {"Select an option"}
|
|
|
|
h3 {"The radio is... {is_playing}!"}
|
|
|
|
button {
|
|
|
|
"Pause"
|
|
|
|
onclick: move |_| state.modify().reduce(PlayerAction::Pause)
|
|
|
|
}
|
|
|
|
button {
|
|
|
|
"Play"
|
|
|
|
onclick: move |_| state.modify().reduce(PlayerAction::Play)
|
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 new() -> Self {
|
|
|
|
Self { is_playing: false }
|
|
|
|
}
|
|
|
|
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",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|