Add simple fetch example.
This commit is contained in:
parent
c3b6a4ddbc
commit
9085d7f0d2
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -290,6 +290,7 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
|
||||
name = "letterbox"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"seed",
|
||||
"wasm-bindgen-test",
|
||||
]
|
||||
|
||||
@ -16,6 +16,7 @@ crate-type = ["cdylib"]
|
||||
wasm-bindgen-test = "0.3.18"
|
||||
|
||||
[dependencies]
|
||||
log = "0.4.14"
|
||||
seed = "0.8.0"
|
||||
|
||||
[profile.release]
|
||||
|
||||
41
src/lib.rs
41
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,17 +29,46 @@ 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<String>),
|
||||
}
|
||||
|
||||
// `update` describes how to handle each `Msg`.
|
||||
fn update(msg: Msg, model: &mut Model, _: &mut impl Orders<Msg>) {
|
||||
fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) {
|
||||
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<String> {
|
||||
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)
|
||||
}
|
||||
|
||||
// ------ ------
|
||||
@ -48,9 +78,12 @@ fn update(msg: Msg, model: &mut Model, _: &mut impl Orders<Msg>) {
|
||||
// `view` describes what to display.
|
||||
fn view(model: &Model) -> Node<Msg> {
|
||||
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()))
|
||||
],
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user