Struct yewdux::dispatch::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.

use std::rc::Rc;

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

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

struct App {
    /// Our local version of state.
    state: Rc<State>,
    /// Our dispatch. Make sure to keep this, or the subscription will be dropped.
    dispatch: Dispatch<State>,
}

enum Msg {
    /// Message to receive new state.
    State(Rc<State>),
}

impl Component for App {
    type Message = Msg;
    type Properties = ();

    fn create(ctx: &Context<Self>) -> Self {
        let on_change = ctx.link().callback(Msg::State);
        let dispatch = Dispatch::global().subscribe(on_change);
        Self {
            state: dispatch.get(),
            dispatch,
        }
    }

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

    /// ...
}
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()
    }
}

let dispatch = Dispatch::<State>::global();
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()
    }
}

let dispatch = Dispatch::<State>::global();
let onclick = dispatch.apply_callback(|_| AddOne);
html! {
    <button {onclick}>{"+1"}</button>
}
source

pub fn set(&self, val: S)

Set state to given value immediately.

let dispatch = Dispatch::<State>::global();
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.

let dispatch = Dispatch::<State>::global();
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.

let dispatch = Dispatch::<State>::global();
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.

let dispatch = Dispatch::<State>::global();
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.

let dispatch = Dispatch::<State>::global();
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.

let dispatch = Dispatch::<State>::global();
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.

let dispatch = Dispatch::<State>::global();
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 copy 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> PartialEq for Dispatch<S>

source§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

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

Auto Trait Implementations§

§

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> !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> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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,

§

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>,

§

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>,

§

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

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<T> CloneAny for T
where T: Any + Clone,

source§

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