snapped async fn

This commit is contained in:
LinlyBoi
2022-12-25 10:10:50 +02:00
parent f1aeeed085
commit 523bae94f2
2 changed files with 29 additions and 9 deletions

View File

@@ -121,14 +121,15 @@ impl Component for RandomCommit {
} }
//Generate Struct and implement component for driver using CommonDriver //Generate Struct and implement component for driver using CommonDriver
struct Driver { struct Driver {
driver: FetchState<CommonDriver>, driver: FetchState<String>,
} }
//implement the component for Driver using a string
impl Component for Driver { impl Component for Driver {
type Message = Msg<CommonDriver>; type Message = Msg<String>;
type Properties = (); type Properties = ();
fn create(_ctx: &Context<Self>) -> Self { fn create(_ctx: &Context<Self>) -> Self {
Self { Self {
driver: FetchState::NotFetching, //Default state is not fetching anything driver: FetchState::NotFetching,
} }
} }
@@ -164,12 +165,11 @@ impl Component for Driver {
} }
fn view(&self, ctx: &Context<Self>) -> Html { fn view(&self, ctx: &Context<Self>) -> Html {
//render the component into HTML
match &self.driver { match &self.driver {
FetchState::NotFetching => html! { FetchState::NotFetching => html! {
<> <>
<button onclick={ctx.link().callback(|_| Msg::GetData)}> <button onclick={ctx.link().callback(|_| Msg::GetData)}>
{ "Get driver info" } { "Get driver" }
</button> </button>
<button onclick={ctx.link().callback(|_| Msg::GetError)}> <button onclick={ctx.link().callback(|_| Msg::GetError)}>
{ "Get using incorrect URL" } { "Get using incorrect URL" }
@@ -177,10 +177,7 @@ impl Component for Driver {
</> </>
}, },
FetchState::Fetching => html! { "Fetching" }, FetchState::Fetching => html! { "Fetching" },
FetchState::Success(data) => match data.clone().use_it() { FetchState::Success(data) => html! { <p> {data} </p> },
Ok(html) => html,
Err(err) => html! { err },
},
FetchState::Failed(err) => html! { err }, FetchState::Failed(err) => html! { err },
} }
} }

View File

@@ -60,3 +60,26 @@
// } // }
// } // }
// } // }
// async fn fetch_driver(url: &'static str) -> Result<CommonDriver, FetchError> {
// let mut opts = RequestInit::new();
// opts.method("GET");
// //Available request modes: Cors, NoCors, SameOrigin
// opts.mode(RequestMode::NoCors); //NoCors because cors simply doesn't work here
//
// let request = Request::new_with_str_and_init(url, &opts)?;
// //api header for json
// request.headers().set("Accept", "application/json")?;
//
// let window = web_sys::window().unwrap();
// let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
// assert!(resp_value.is_instance_of::<Response>());
// let resp: Response = resp_value.dyn_into().unwrap();
//
// //parsing Json response
// let fetched_json = JsFuture::from(resp.json()?).await?;
// log!(fetched_json.clone());
// let fetched_json: JsValue = fetched_json.into();
// //parsing into CommonDriver struct
// let fetched_json: CommonDriver = fetched_json.into_serde().unwrap();
// Ok(fetched_json)
// }