added "tell me another" button

This commit is contained in:
Bart Massey 2024-06-02 22:22:47 -07:00
parent eb45baf455
commit d69cc7d019
3 changed files with 25 additions and 6 deletions

View File

@ -1,6 +1,7 @@
<!doctype html>
<html lang="en">
<head>
<title>Knock Knock!</title>
<link data-trunk rel="css" href="index.css" />
</head>
<body></body>

View File

@ -10,8 +10,15 @@ pub struct JokeStruct {
}
impl JokeStruct {
pub async fn get_joke() -> Msg {
let response = http::Request::get("http://localhost:3000/api/v1/joke")
pub async fn get_joke(key: Option<String>) -> Msg {
let request = match &key {
None => "http://localhost:3000/api/v1/joke".to_string(),
Some(ref key) => format!(
"http://localhost:3000/api/v1/joke?id={}",
key,
),
};
let response = http::Request::get(&request)
.send()
.await;
match response {

View File

@ -22,6 +22,14 @@ struct App {
pub enum Msg {
GotJoke(JokeResult),
GetJoke(Option<String>),
}
impl App {
fn refresh_joke(ctx: &Context<Self>, key: Option<String>) {
let got_joke = JokeStruct::get_joke(key);
ctx.link().send_future(got_joke);
}
}
impl Component for App {
@ -30,20 +38,20 @@ impl Component for App {
fn create(ctx: &Context<Self>) -> Self {
let cookie = acquire_cookie();
let got_joke = JokeStruct::get_joke();
ctx.link().send_future(got_joke);
App::refresh_joke(ctx, None);
let joke = Err(gloo_net::Error::GlooError("Loading Joke…".to_string()));
Self { cookie, joke }
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::GotJoke(joke) => self.joke = joke,
Msg::GetJoke(key) => App::refresh_joke(ctx, key),
}
true
}
fn view(&self, _ctx: &Context<Self>) -> Html {
fn view(&self, ctx: &Context<Self>) -> Html {
let cookie = &self.cookie;
let joke = &self.joke;
html! {
@ -60,6 +68,9 @@ impl Component for App {
<span class="error">{format!("Server Error: {error}")}</span>
</div>
}
<div>
<button onclick={ctx.link().callback(|_| Msg::GetJoke(None))}>{"Tell me another!"}</button>
</div>
</>
}
}