Module effect

Module effect 

Source
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) -> bool

An 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§

DispatchResult
Result of dispatching an action to an effect-aware store.
EffectStore
A store that supports effect-emitting reducers.
EffectStoreWithMiddleware
An effect store with middleware support.

Type Aliases§

EffectReducer
A reducer function that can emit effects.