summaryrefslogtreecommitdiff
path: root/webapp/src/components/app_context_provider.rs
blob: f2938ffa60ffde2369def822a2732d4b69165734 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use gloo_net::http::Request;
use protocol::UserInfo;
use std::rc::Rc;
use yew::prelude::*;

#[derive(Clone, Debug, PartialEq)]
pub struct AppContext {
    pub user: Option<UserInfo>,
}

#[derive(Properties, Clone, PartialEq)]
pub struct Props {
    pub children: Children,
}

#[function_component(AppContextProvider)]
pub fn app_context_provider(props: &Props) -> Html {
    let context: UseStateHandle<Option<Rc<AppContext>>> = use_state(|| None);

    {
        let context = context.clone();
        use_effect_with_deps(
            move |_| {
                wasm_bindgen_futures::spawn_local(async move {
                    let user_info: Option<UserInfo> = Request::get("/api/user/info")
                        .send()
                        .await
                        .unwrap()
                        .json()
                        .await
                        .unwrap();
                    context.set(Some(Rc::new(AppContext { user: user_info })));
                });
                || ()
            },
            (),
        );
    }

    match &*context {
        None => html! {
            <p>{ "Loading app..." }</p>
        },
        Some(context) => html! {
            <ContextProvider<Rc<AppContext>> {context}>
                { for props.children.iter() }
            </ContextProvider<Rc<AppContext>>>
        },
    }
}