Function yew_agent::use_bridge
source · pub fn use_bridge<'hook, T, F>(
on_output: F
) -> impl 'hook + Hook<Output = UseBridgeHandle<T>>where
T: Bridged,
F: Fn(T::Output) + 'static,
T: 'hook,
F: 'hook,
Expand description
A hook to bridge to an Worker
.
This hooks will only bridge the worker once over the entire component lifecycle.
Takes a callback as the only argument. The callback will be updated on every render to make sure captured values (if any) are up to date.
Examples
use serde::{Deserialize, Serialize};
use yew::prelude::*;
use yew_agent::{use_bridge, UseBridgeHandle};
// This would usually live in the same file as your worker
#[derive(Serialize, Deserialize)]
pub enum WorkerResponseType {
IncrementCounter,
}
use my_worker_mod::MyWorker; // note that <MyWorker as yew_agent::Worker>::Output == WorkerResponseType
#[function_component(UseBridge)]
fn bridge() -> Html {
let counter = use_state(|| 0);
// a scoped block to clone the state in
{
let counter = counter.clone();
// response will be of type MyWorker::Output, i.e. WorkerResponseType
let bridge: UseBridgeHandle<MyWorker> = use_bridge(move |response| match response {
WorkerResponseType::IncrementCounter => {
counter.set(*counter + 1);
}
});
}
html! {
<div>
{*counter}
</div>
}
}
Note
When used in function components and hooks, this hook is equivalent to:
pub fn use_bridge<T, F>(on_output: F) -> UseBridgeHandle<T>
where
T: Bridged,
F: Fn(T::Output) + 'static,
{
/* implementation omitted */
}