diff --git a/Cargo.lock b/Cargo.lock index 7617d94..080f192 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -290,6 +290,7 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" name = "letterbox" version = "0.1.0" dependencies = [ + "log", "seed", "wasm-bindgen-test", ] diff --git a/Cargo.toml b/Cargo.toml index 9c63714..ad34c2a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ crate-type = ["cdylib"] wasm-bindgen-test = "0.3.18" [dependencies] +log = "0.4.14" seed = "0.8.0" [profile.release] diff --git a/src/lib.rs b/src/lib.rs index fde0edf..52784dd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ // but some rules are too "annoying" or are not applicable for your case.) #![allow(clippy::wildcard_imports)] +use log::info; use seed::{prelude::*, *}; // ------ ------ @@ -28,19 +29,48 @@ struct Model { // ------ ------ // (Remove the line below once any of your `Msg` variants doesn't implement `Copy`.) -#[derive(Copy, Clone)] // `Msg` describes the different events you can modify state with. enum Msg { Increment, + SearchRequest(String), + // TODO(wathiede): replace String with serde json decoded struct + SearchResult(fetch::Result), } // `update` describes how to handle each `Msg`. -fn update(msg: Msg, model: &mut Model, _: &mut impl Orders) { +fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders) { match msg { Msg::Increment => model.counter += 1, + Msg::SearchRequest(query) => { + orders + .skip() + .perform_cmd(async { Msg::SearchResult(search_request(query).await) }); + } + + Msg::SearchResult(Ok(response_data)) => { + info!("fetch ok {}", response_data); + } + + Msg::SearchResult(Err(fetch_error)) => { + info!("fetch failed {:?}", fetch_error); + } } } +async fn search_request(query: String) -> fetch::Result { + Request::new(get_search_request_url(query)) + .method(Method::Get) + .fetch() + .await? + .check_status()? + .json() + .await +} + +fn get_search_request_url(query: String) -> String { + format!("http://localhost:1234/search?q={}", query) +} + // ------ ------ // View // ------ ------ @@ -48,9 +78,12 @@ fn update(msg: Msg, model: &mut Model, _: &mut impl Orders) { // `view` describes what to display. fn view(model: &Model) -> Node { div![ - "This is a counter: ", + "Modified This is a counter: ", C!["counter"], - button![model.counter, ev(Ev::Click, |_| Msg::Increment),], + button![ + model.counter, + ev(Ev::Click, |_| Msg::SearchRequest("hello".to_string())) + ], ] }