add use_bridge docs (#2722)

* init use_bridge content

* cargo fmt

* cargo +nightly fmt --all

* more sensible code

* make example compile

* make example compile (for real this time)

* update docs

* oops

* oops

* make super work

* this is rust, not C
This commit is contained in:
Shrey Sudhir 2022-06-25 04:17:58 +10:00 committed by GitHub
parent 467267d799
commit f82af86c66
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 67 additions and 0 deletions

View File

@ -10,3 +10,6 @@ license = "MIT OR Apache-2.0"
[dependencies]
yew = { version = "0.19.3", path = "../yew" }
gloo-worker = "0.1"
[dev-dependencies]
serde = "1.0.137"

View File

@ -30,6 +30,70 @@ where
///
/// 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
///
/// ```
/// # mod example {
/// 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,
/// }
/// # mod my_worker_mod {
/// # use yew_agent::{HandlerId, Public, WorkerLink};
/// # use super::WorkerResponseType;
/// # pub struct MyWorker {
/// # pub link: WorkerLink<Self>,
/// # }
///
/// # impl yew_agent::Worker for MyWorker {
/// # type Input = ();
/// # type Output = WorkerResponseType;
/// # type Reach = Public<Self>;
/// # type Message = ();
/// #
/// # fn create(link: WorkerLink<Self>) -> Self {
/// # MyWorker { link }
/// # }
/// #
/// # fn update(&mut self, _msg: Self::Message) {
/// # // do nothing
/// # }
/// #
/// # fn handle_input(&mut self, _msg: Self::Input, id: HandlerId) {
/// # self.link.respond(id, 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>
/// }
/// }
/// # }
/// ```
#[hook]
pub fn use_bridge<T, F>(on_output: F) -> UseBridgeHandle<T>
where