From d69cc7d0190d8ad7129dce432113366b28bf14b9 Mon Sep 17 00:00:00 2001 From: Bart Massey Date: Sun, 2 Jun 2024 22:22:47 -0700 Subject: [PATCH] added "tell me another" button --- index.html | 1 + src/joke.rs | 11 +++++++++-- src/main.rs | 19 +++++++++++++++---- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/index.html b/index.html index 0b36743..7335dbc 100644 --- a/index.html +++ b/index.html @@ -1,6 +1,7 @@ + Knock Knock! diff --git a/src/joke.rs b/src/joke.rs index ad1bafa..4f64950 100644 --- a/src/joke.rs +++ b/src/joke.rs @@ -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) -> 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 { diff --git a/src/main.rs b/src/main.rs index 12b5228..1eb8f53 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,6 +22,14 @@ struct App { pub enum Msg { GotJoke(JokeResult), + GetJoke(Option), +} + +impl App { + fn refresh_joke(ctx: &Context, key: Option) { + 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 { 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, msg: Self::Message) -> bool { + fn update(&mut self, ctx: &Context, 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) -> Html { + fn view(&self, ctx: &Context) -> Html { let cookie = &self.cookie; let joke = &self.joke; html! { @@ -60,6 +68,9 @@ impl Component for App { {format!("Server Error: {error}")} } +
+ +
} }