Expand description
§Yew Data Link
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:
- Implement
MsgData
for your data type. - Create link in component A via
use_link
. - Create data in component B via
use_data
. - Pass link from A to B and bind it via
use_bind_link
. - Mutate data with
UseLinkHandle::msg
andUseDataHandle::msg
. - Read data with
UseDataHandle::current
.
§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§
- UseData
Handle - A handle for
use_data
hook. - UseLink
Handle - 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.