Skip to main content

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) -> ReducerResult<E>

§Example

use tui_dispatch_core::{Action, ReducerResult, EffectStore};

// Define your effects
enum Effect {
    FetchData { url: String },
    CopyToClipboard(String),
}

// Define state and actions
struct AppState { loading: bool, data: Option<String> }

#[derive(Clone, Debug)]
enum AppAction { LoadData, DidLoadData(String) }

impl Action for AppAction {
    fn name(&self) -> &'static str {
        match self {
            AppAction::LoadData => "LoadData",
            AppAction::DidLoadData(_) => "DidLoadData",
        }
    }
}

// Reducer emits effects
fn reducer(state: &mut AppState, action: AppAction) -> ReducerResult<Effect> {
    match action {
        AppAction::LoadData => {
            state.loading = true;
            ReducerResult::changed_with(
                Effect::FetchData { url: "https://api.example.com".into() }
            )
        }
        AppAction::DidLoadData(data) => {
            state.loading = false;
            state.data = Some(data);
            ReducerResult::changed()
        }
    }
}

// Main loop handles effects
let mut store = EffectStore::new(
    AppState { loading: false, data: None },
    reducer,
);
let result = store.dispatch(AppAction::LoadData);
assert!(result.changed);

for effect in result.effects {
    match effect {
        Effect::FetchData { url } => { /* spawn async task */ }
        _ => {}
    }
}

Structs§

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

Type Aliases§

EffectReducer
A reducer function that can emit effects.