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.
|
2022-01-03 05:42:17 +00:00
|
|
|
//!
|
|
|
|
//! Currently we don't have a reducer pattern hook. If you'd like to add it,
|
|
|
|
//! feel free to make a PR.
|
2021-06-24 02:32:54 +00:00
|
|
|
|
|
|
|
use dioxus::prelude::*;
|
2022-01-03 05:42:17 +00:00
|
|
|
|
2021-07-08 13:29:12 +00:00
|
|
|
fn main() {
|
2022-01-02 23:35:38 +00:00
|
|
|
dioxus::desktop::launch(app);
|
2021-07-08 13:29:12 +00:00
|
|
|
}
|
2021-06-24 02:32:54 +00:00
|
|
|
|
2022-01-02 23:35:38 +00:00
|
|
|
fn app(cx: Scope) -> Element {
|
2022-01-26 02:41:40 +00:00
|
|
|
let (state, set_state) = use_state(&cx, PlayerState::new);
|
2021-06-24 02:32:54 +00:00
|
|
|
|
2021-12-30 08:14:47 +00:00
|
|
|
cx.render(rsx!(
|
|
|
|
div {
|
|
|
|
h1 {"Select an option"}
|
2022-01-03 05:42:17 +00:00
|
|
|
h3 { "The radio is... " [state.is_playing()] "!" }
|
2022-01-26 02:41:40 +00:00
|
|
|
button { onclick: move |_| set_state.make_mut().reduce(PlayerAction::Pause),
|
2021-12-30 08:14:47 +00:00
|
|
|
"Pause"
|
|
|
|
}
|
2022-01-26 02:41:40 +00:00
|
|
|
button { onclick: move |_| set_state.make_mut().reduce(PlayerAction::Play),
|
2021-12-30 08:14:47 +00:00
|
|
|
"Play"
|
|
|
|
}
|
2021-06-24 02:32:54 +00:00
|
|
|
}
|
2021-12-30 08:14:47 +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 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",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|