perspective_viewer/utils/hooks/use_async_callback.rs
1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
5// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors. ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use wasm_bindgen::__rt::IntoJsResult;
14use wasm_bindgen::JsValue;
15use wasm_bindgen_futures::future_to_promise;
16use yew::prelude::*;
17
18/// Just like `use_callback`, except convenient for an async result body.
19#[hook]
20pub fn use_async_callback<IN, OUT, F, D>(deps: D, f: F) -> Callback<IN, ()>
21where
22 IN: Clone + 'static,
23 OUT: IntoJsResult + 'static,
24 F: AsyncFn(IN, &D) -> OUT + 'static,
25 D: Clone + PartialEq + 'static,
26{
27 use std::rc::Rc;
28
29 let deps = Rc::new(deps);
30 let f = Rc::new(f);
31 (*use_memo(deps, move |deps| {
32 let deps = deps.clone();
33 let ff = move |value: IN| {
34 perspective_client::clone!(value, f, deps);
35 let _ = future_to_promise(async move {
36 f(value, &deps).await.into_js_result()?;
37 Ok(JsValue::UNDEFINED)
38 });
39 };
40 Callback::from(ff)
41 }))
42 .clone()
43}