pub fn use_slice<'hook, T>() -> impl 'hook + Hook<Output = UseSliceHandle<T>>where
T: Slice + 'static + 'hook,
Expand description
A hook to connect to a Slice
.
Returns a UseSliceHandle<T>
.
Example
enum CounterAction {
Increment,
Decrement,
}
#[derive(PartialEq, Default, Slice)]
struct Counter(u64);
impl Reducible for Counter {
type Action = CounterAction;
fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
match action {
CounterAction::Increment => Self(self.0 + 1).into(),
CounterAction::Decrement => Self(self.0 - 1).into(),
}
}
}
#[function_component(CounterComp)]
fn counter_comp() -> Html {
let ctr = use_slice::<Counter>();
let inc = {
let ctr = ctr.clone();
Callback::from(move |_| {ctr.dispatch(CounterAction::Increment);})
};
let dec = {
let ctr = ctr.clone();
Callback::from(move |_| {ctr.dispatch(CounterAction::Decrement);})
};
html! {
<div>
<div>{"Current Counter: "}{ctr.0}</div>
<button onclick={inc}>{"Increase"}</button>
<button onclick={dec}>{"Decrease"}</button>
</div>
}
}
Note
When used in function components and hooks, this hook is equivalent to:
pub fn use_slice<T>() -> UseSliceHandle<T>
where
T: Slice + 'static,
{
/* implementation omitted */
}