Expand description
Effect-based state management
This module provides an effect-aware store that allows reducers to emit side effects alongside state changes. Effects are declarative descriptions of work to be done, not the work itself.
§Overview
The traditional reducer returns bool (state changed or not):
ⓘ
fn reducer(state: &mut S, action: A) -> boolAn effect-aware reducer returns both change status and effects:
ⓘ
fn reducer(state: &mut S, action: A) -> DispatchResult<E>§Example
ⓘ
use tui_dispatch::{Action, DispatchResult, EffectStore};
// Define your effects
enum Effect {
FetchData { url: String },
SaveToFile { path: String, data: Vec<u8> },
CopyToClipboard(String),
}
// Define state and actions
struct AppState { loading: bool, data: Option<String> }
#[derive(Clone, Debug, Action)]
enum AppAction {
LoadData,
DidLoadData(String),
}
// Reducer emits effects
fn reducer(state: &mut AppState, action: AppAction) -> DispatchResult<Effect> {
match action {
AppAction::LoadData => {
state.loading = true;
DispatchResult::changed_with(vec![
Effect::FetchData { url: "https://api.example.com".into() }
])
}
AppAction::DidLoadData(data) => {
state.loading = false;
state.data = Some(data);
DispatchResult::changed()
}
}
}
// Main loop handles effects
let mut store = EffectStore::new(AppState::default(), reducer);
let result = store.dispatch(AppAction::LoadData);
for effect in result.effects {
match effect {
Effect::FetchData { url } => {
// spawn async task
}
// ...
}
}Structs§
- Dispatch
Result - Result of dispatching an action to an effect-aware store.
- Effect
Store - A store that supports effect-emitting reducers.
- Effect
Store With Middleware - An effect store with middleware support.
Type Aliases§
- Effect
Reducer - A reducer function that can emit effects.