use gloo::{console::log, utils::format::JsValueSerdeExt};
use std::{
error::Error,
fmt::{self, Debug, Display, Formatter},
};
use wasm_bindgen::{JsCast, JsValue};
use common::{CommonAdmin, CommonDriver};
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};
use yew::{html, Component, Context, Html};
//Trait to handle Future yew HTMLS
pub trait UseAble {
//Return HTML if didn't fail return error if not
fn use_it(self) -> Result;
}
impl UseAble for CommonDriver {
fn use_it(self) -> Result {
let name = self.name;
let email = self.address;
let id = self.id;
let html = html! {
{ "Driver:" }
{ format!("Name: {}", name) }
{ format!("Email: {}", email) }
{ format!("ID: {}", id) }
};
Ok(html)
}
}
impl UseAble for CommonAdmin {
fn use_it(self) -> Result {
let name = self.name;
let email = self.address;
let id = self.id;
let html = html! {
{ "Admin:" }
{ format!("Name: {}", name) }
{ format!("Email: {}", email) }
{ format!("ID: {}", id) }
};
Ok(html)
}
}
//Wwasm bingdengen code
const DRIVER_URL: &str = "http://db.sewelam.tech/api/driver/1234";
const FUNNY_TXT_URL: &str = "https://whatthecommit.com/index.txt";
const INCORRECT_URL: &str = "http://libkyy.cf";
//Generic Msg for our states
enum Msg {
SetDataFetchState(FetchState),
GetData,
GetError,
}
struct RandomCommit {
commit: FetchState,
}
//This trait is for all yew components
impl Component for RandomCommit {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context) -> Self {
Self {
commit: FetchState::NotFetching, //Default state is not fetching anything
}
}
fn update(&mut self, ctx: &Context, msg: Self::Message) -> bool {
match msg {
Msg::SetDataFetchState(fetch_state) => {
self.commit = fetch_state;
true
}
Msg::GetData => {
ctx.link().send_future(async {
match fetch_commit(FUNNY_TXT_URL).await {
Ok(commit) => Msg::SetDataFetchState(FetchState::Success(commit)),
Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetDataFetchState(FetchState::Fetching));
false
}
Msg::GetError => {
ctx.link().send_future(async {
match fetch_commit(INCORRECT_URL).await {
Ok(commit) => Msg::SetDataFetchState(FetchState::Success(commit)),
Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetDataFetchState(FetchState::Fetching));
false
}
}
}
fn view(&self, ctx: &Context) -> Html {
match &self.commit {
FetchState::NotFetching => html! {
<>
>
},
FetchState::Fetching => html! { "Fetching" },
FetchState::Success(data) => {
html! { <>