yew-api-hook

Crates.ioyew-api-hook
lib.rsyew-api-hook
version0.3.0
sourcesrc
created_at2023-01-10 13:47:16.327136
updated_at2023-01-21 11:36:14.53063
descriptionUse asynchronous api requests in conjunction with yew's suspense feature
homepagehttps://github.com/mara214/yew-api-hook
repositoryhttps://github.com/mara214/yew-api-hook.git
max_upload_size
id755334
size20,440
Mara Schulke (mara-schulke)

documentation

README

crates.io docs

Yew API Hook

Use asynchronous api requests in conjunction with yew's suspense feature

Usage

#[function_component]
fn App() -> Html {
    html! {
        <Suspense fallback={html! { {"Loading.."} }}>
            <AsyncComponent />
        </Suspense>
    }
}

#[function_component]
fn AsyncComponent() -> HtmlResult {
    let data = use_api(requests::Fetch { id: 0 })?;

    match data {
        Ok(json) => Ok(html! { {format!("{:#?}", json)} }),
        Err(_) => Ok(html! { {"An error occured"} })
    }
}

mod requests {
    use yew_api_hook::prelude::*;

    type ApiResult = anyhow::Result<serde_json::Value>;

    #[derive(Clone, Debug, PartialEq)]
    pub struct Fetch {
        pub id: u64
    }

    #[async_trait(?Send)]
    impl Request for Fetch {
        type Error = anyhow::Error;
        type Output = serde_json::Value;

        async fn run(&self) -> ApiResult {
            // Use your favorite http or whatever implementation
            get(format!("/entity/{}", self.id)).await
        }
    }
}
Commit count: 7

cargo fmt