Skip to main content

Dispatch

Struct Dispatch 

Source
pub struct Dispatch<S: Store> { /* private fields */ }
Expand description

The primary interface to a Store.

Implementations§

Source§

impl<S: Store> Dispatch<S>

Source

pub fn global() -> Self

Create a new dispatch with the global context (thread local).

This is only available for wasm. For SSR, see the YewduxRoot pattern.

Source

pub fn new(cx: &Context) -> Self

Create a new dispatch with access to the given context.

Source

pub fn context(&self) -> &Context

Get the context used by this dispatch.

Source

pub fn spawn_future<F, FU>(&self, f: F)
where F: FnOnce(Self) -> FU, FU: Future<Output = ()> + 'static,

Spawn a future with access to this dispatch.

Source

pub fn future_callback<E, F, FU>(&self, f: F) -> Callback<E>
where F: Fn(Self) -> FU + 'static, FU: Future<Output = ()> + 'static,

Create a callback that will spawn a future with access to this dispatch.

Source

pub fn future_callback_with<E, F, FU>(&self, f: F) -> Callback<E>
where F: Fn(Self, E) -> FU + 'static, FU: Future<Output = ()> + 'static,

Create a callback that will spawn a future with access to this dispatch and the emitted event.

Source

pub fn subscribe<C: Callable<S>>(self, on_change: C) -> Self

Create a dispatch that subscribes to changes in state. Latest state is sent immediately, and on every subsequent change. Automatically unsubscribes when this dispatch is dropped.

§Higher-Order Component Pattern with YewduxRoot
use std::rc::Rc;

use yew::prelude::*;
use yewdux::prelude::*;

#[derive(Default, Clone, PartialEq, Eq, Store)]
struct State {
    count: u32,
}

// Props for our struct component
#[derive(Properties, PartialEq, Clone)]
struct CounterProps {
    dispatch: Dispatch<State>,
}

// Message type for state updates
enum Msg {
    StateChanged(Rc<State>),
}

// Our struct component that uses the state
struct Counter {
    state: Rc<State>,
    dispatch: Dispatch<State>,
}

impl Component for Counter {
    type Message = Msg;
    type Properties = CounterProps;

    fn create(ctx: &Context<Self>) -> Self {
        // Subscribe to state changes
        let callback = ctx.link().callback(Msg::StateChanged);
        let dispatch = ctx.props().dispatch.clone().subscribe_silent(callback);
         
        Self {
            state: dispatch.get(),
            dispatch,
        }
    }

    fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            Msg::StateChanged(state) => {
                self.state = state;
                true
            }
        }
    }

    fn view(&self, _ctx: &Context<Self>) -> Html {
        let count = self.state.count;
        let onclick = self.dispatch.reduce_mut_callback(|s| s.count += 1);
         
        html! {
            <>
                <h1>{ count }</h1>
                <button {onclick}>{"+1"}</button>
            </>
        }
    }
}

// Higher-Order Component (HOC) that accesses the context
#[function_component]
fn CounterHoc() -> Html {
    // Use the hook to get the dispatch from context
    let dispatch = use_dispatch::<State>();
     
    html! {
        <Counter {dispatch} />
    }
}

// App component with YewduxRoot for SSR support
#[function_component]
fn App() -> Html {
    html! {
        <YewduxRoot>
            <CounterHoc />
        </YewduxRoot>
    }
}
Source

pub fn subscribe_silent<C: Callable<S>>(self, on_change: C) -> Self

Create a dispatch that subscribes to changes in state. Similar to Self::subscribe, however state is not sent immediately. Automatically unsubscribes when this dispatch is dropped.

Source

pub fn get(&self) -> Rc<S>

Get the current state.

Source

pub fn apply<R: Reducer<S>>(&self, reducer: R)

Apply a Reducer immediately.

#[derive(Default, Clone, PartialEq, Eq, Store)]
struct State {
    count: u32,
}

struct AddOne;
impl Reducer<State> for AddOne {
    fn apply(self, state: Rc<State>) -> Rc<State> {
        State {
            count: state.count + 1,
        }
        .into()
    }
}

// Apply a reducer to update the state
dispatch.apply(AddOne);
Source

pub fn apply_callback<E, M, F>(&self, f: F) -> Callback<E>
where M: Reducer<S>, F: Fn(E) -> M + 'static,

Create a callback that applies a Reducer.

#[derive(Default, Clone, PartialEq, Eq, Store)]
struct State {
    count: u32,
}

struct AddOne;
impl Reducer<State> for AddOne {
    fn apply(self, state: Rc<State>) -> Rc<State> {
        State {
            count: state.count + 1,
        }
        .into()
    }
}

// Create a callback that will update the state when triggered
let onclick = dispatch.apply_callback(|_| AddOne);
html! {
    <button {onclick}>{"+1"}</button>
}
Source

pub fn set(&self, val: S)

Set state to given value immediately.

// Set the state to a new value
dispatch.set(State { count: 0 });
Source

pub fn set_callback<E, F>(&self, f: F) -> Callback<E>
where F: Fn(E) -> S + 'static,

Set state using value from callback.

let dispatch = use_dispatch::<State>();
let onchange = dispatch.set_callback(|event: Event| {
    let value = event.target_unchecked_into::<web_sys::HtmlInputElement>().value();
    State { count: value.parse().unwrap() }
});
html! {
    <input type="number" placeholder="Enter a number" {onchange}  />
}
Source

pub fn reduce<F>(&self, f: F)
where F: FnOnce(Rc<S>) -> Rc<S>,

Change state immediately.

// Transform the current state into a new state
dispatch.reduce(|state| State { count: state.count + 1 }.into());
Source

pub fn reduce_callback<F, E>(&self, f: F) -> Callback<E>
where F: Fn(Rc<S>) -> Rc<S> + 'static, E: 'static,

Create a callback that changes state.

// Create a callback that will transform the state when triggered
let onclick = dispatch.reduce_callback(|state| State { count: state.count + 1 }.into());
html! {
    <button {onclick}>{"+1"}</button>
}
Source

pub fn reduce_callback_with<F, E>(&self, f: F) -> Callback<E>
where F: Fn(Rc<S>, E) -> Rc<S> + 'static, E: 'static,

Similar to Self::reduce_callback but also provides the fired event.

// Create a callback that will transform the state using the event data
let onchange = dispatch.reduce_callback_with(|state, event: Event| {
    let value = event.target_unchecked_into::<web_sys::HtmlInputElement>().value();
    State {
        count: value.parse().unwrap()
    }
    .into()
});
html! {
    <input type="number" placeholder="Enter a number" {onchange}  />
}
Source

pub fn reduce_mut<F, R>(&self, f: F) -> R
where S: Clone, F: FnOnce(&mut S) -> R,

Mutate state with given function.

// Mutate the state in-place
dispatch.reduce_mut(|state| state.count += 1);
Source

pub fn reduce_mut_callback<F, R, E>(&self, f: F) -> Callback<E>
where S: Clone, F: Fn(&mut S) -> R + 'static, E: 'static,

Like Self::reduce_mut but from a callback.

// Create a callback that will mutate the state in-place when triggered
let onclick = dispatch.reduce_mut_callback(|s| s.count += 1);
html! {
    <button {onclick}>{"+1"}</button>
}
Source

pub fn reduce_mut_callback_with<F, R, E>(&self, f: F) -> Callback<E>
where S: Clone, F: Fn(&mut S, E) -> R + 'static, E: 'static,

Similar to Self::reduce_mut_callback but also provides the fired event.

// Create a callback that will mutate the state using event data
let onchange = dispatch.reduce_mut_callback_with(|state, event: Event| {
    let value = event.target_unchecked_into::<web_sys::HtmlInputElement>().value();
    state.count = value.parse().unwrap();
});
html! {
    <input type="number" placeholder="Enter a number" {onchange}  />
}

Trait Implementations§

Source§

impl<S: Store> Clone for Dispatch<S>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<S: Store> Debug for Dispatch<S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<S: Store> Default for Dispatch<S>

Available on crate feature doctests or WebAssembly only.
Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<S: Store> PartialEq for Dispatch<S>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl<S> !Freeze for Dispatch<S>

§

impl<S> !RefUnwindSafe for Dispatch<S>

§

impl<S> !Send for Dispatch<S>

§

impl<S> !Sync for Dispatch<S>

§

impl<S> Unpin for Dispatch<S>

§

impl<S> UnsafeUnpin for Dispatch<S>

§

impl<S> !UnwindSafe for Dispatch<S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoPropValue<Option<T>> for T

Source§

fn into_prop_value(self) -> Option<T>

Convert self to a value of a Properties struct.
Source§

impl<T> IntoPropValue<T> for T

Source§

fn into_prop_value(self) -> T

Convert self to a value of a Properties struct.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<Token, Builder, How> AllPropsFor<Builder, How> for Token
where Builder: Buildable<Token>, <Builder as Buildable<Token>>::WrappedToken: HasAllProps<<Builder as Buildable<Token>>::Output, How>,

Source§

impl<T> HasAllProps<(), T> for T