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_futures::future_to_promise;
15use yew::prelude::*;
16
17use crate::renderer::*;
18use crate::session::*;
19use crate::*;
20
21#[derive(Clone, Properties, PartialEq)]
22pub struct StatusIndicatorProps {
23    pub session: Session,
24    pub renderer: Renderer,
25    pub children: Children,
26}
27
28/// Just like `use_callback`, except convenient for an async cresult body.
29#[hook]
30pub fn use_async_callback<IN, OUT, F, D>(deps: D, f: F) -> Callback<IN, ()>
31where
32    IN: Clone + 'static,
33    OUT: IntoJsResult + 'static,
34    F: AsyncFn(IN, &D) -> OUT + 'static,
35    D: Clone + PartialEq + 'static,
36{
37    let deps = std::rc::Rc::new(deps);
38    let f = std::rc::Rc::new(f);
39    (*use_memo(deps, move |deps| {
40        let deps = deps.clone();
41        let ff = move |value: IN| {
42            let value = value.clone();
43            let f = f.clone();
44            let deps = deps.clone();
45            let _ = future_to_promise(async move {
46                f(value, &deps).await.into_js_result()?;
47                Ok(JsValue::UNDEFINED)
48            });
49        };
50        Callback::from(ff)
51    }))
52    .clone()
53}