Crate yew_data_link

Source
Expand description

This crate allows one to mutate yew function component’s data from other component via sending messages.

§Usage

To mutate state of component B from component A:

§Example

use yew::prelude::*;
use yew_autoprops::autoprops;
use yew_data_link::{use_bind_link, use_data, use_link, MsgData, UseLinkHandle};

struct Num(i64);

enum NumMsg {
    Inc,
    Dec,
}

impl MsgData for Num {
    type Msg = NumMsg;

    fn msg(&mut self, msg: NumMsg) {
        match msg {
            NumMsg::Inc => self.0 += 1,
            NumMsg::Dec => self.0 -= 1,
        };
    }
}

#[autoprops]
#[function_component]
fn Counter(#[prop_or_default] link: &UseLinkHandle<Num>) -> Html {
    let num = use_data(|| Num(0));
    use_bind_link(link.clone(), num.clone());

    html! {
        <div>{num.current().0}</div>
    }
}

#[function_component]
fn App() -> Html {
    let link = use_link();

    html! {
        <div>
            <button onclick={
                let link = link.clone();
                move |_| link.msg(NumMsg::Inc)
            }>{"+"}</button>

            <Counter link={link.clone()} />

            <button onclick={
                let link = link.clone();
                move |_| link.msg(NumMsg::Dec)
            }>{"-"}</button>
        </div>
    }
}

fn main() {
    yew::Renderer::<App>::new().render();
}

Check examples folder for more.

Structs§

UseDataHandle
A handle for use_data hook.
UseLinkHandle
A handle for use_link hook.

Traits§

MsgData
A trait that is implemented on data to make it mutable by messages.

Functions§

use_bind_link
Binds a link to a data.
use_data
A hook to manage component’s data, that can be mutated from other components.
use_link
Create a link, that can be used to mutate other component’s data.