Function create_reducer
pub fn create_reducer<T, Msg>(
initial: T,
reduce: impl FnMut(&T, Msg) -> T,
) -> (ReadSignal<T>, impl Fn(Msg))
Expand description
An alternative to create_signal
that uses a reducer to get the next
value.
It uses a reducer function that takes the previous value and a message and returns the next value.
Returns a ReadSignal
and a dispatch function to send messages to the reducer.
§Params
initial
- The initial value of the state.reducer
- A function that takes the previous value and a message and returns the next value.
§Example
enum Msg {
Increment,
Decrement,
}
let (state, dispatch) = create_reducer(0, |&state, msg: Msg| match msg {
Msg::Increment => state + 1,
Msg::Decrement => state - 1,
});
assert_eq!(state.get(), 0);
dispatch(Msg::Increment);
assert_eq!(state.get(), 1);
dispatch(Msg::Decrement);
assert_eq!(state.get(), 0);