-
-
Notifications
You must be signed in to change notification settings - Fork 586
/
lib.rs
108 lines (96 loc) · 3.32 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use leptos::prelude::*;
use leptos::tachys::html::style::style;
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cat {
url: String,
}
#[derive(Error, Clone, Debug)]
pub enum CatError {
#[error("Please request more than zero cats.")]
NonZeroCats,
}
type CatCount = usize;
async fn fetch_cats(count: CatCount) -> Result<Vec<String>> {
if count > 0 {
gloo_timers::future::TimeoutFuture::new(1000).await;
// make the request
let res = reqwasm::http::Request::get(&format!(
"https://api.thecatapi.com/v1/images/search?limit={count}",
))
.send()
.await?
// convert it to JSON
.json::<Vec<Cat>>()
.await?
// extract the URL field for each cat
.into_iter()
.take(count)
.map(|cat| cat.url)
.collect::<Vec<_>>();
Ok(res)
} else {
Err(CatError::NonZeroCats)?
}
}
pub fn fetch_example() -> impl IntoView {
let (cat_count, set_cat_count) = signal::<CatCount>(1);
// we use new_unsync here because the reqwasm request type isn't Send
// if we were doing SSR, then
// 1) we'd want to use a Resource, so the data would be serialized to the client
// 2) we'd need to make sure there was a thread-local spawner set up
let cats = AsyncDerived::new_unsync(move || fetch_cats(cat_count.get()));
let fallback = move |errors: ArcRwSignal<Errors>| {
let error_list = move || {
errors.with(|errors| {
errors
.iter()
.map(|(_, e)| view! { <li>{e.to_string()}</li> })
.collect::<Vec<_>>()
})
};
view! {
<div class="error">
<h2>"Error"</h2>
<ul>{error_list}</ul>
</div>
}
};
let spreadable = style(("background-color", "AliceBlue"));
view! {
<div>
<label>
"How many cats would you like?"
<input
type="number"
prop:value=move || cat_count.get().to_string()
on:input:target=move |ev| {
let val = ev.target().value().parse::<CatCount>().unwrap_or(0);
set_cat_count.set(val);
}
/>
</label>
<Transition fallback=|| view! { <div>"Loading..."</div> } {..spreadable}>
<ErrorBoundary fallback>
<ul>
{move || Suspend(async move {
cats.await
.map(|cats| {
cats.iter()
.map(|s| {
view! {
<li>
<img src=s.clone()/>
</li>
}
})
.collect::<Vec<_>>()
})
})}
</ul>
</ErrorBoundary>
</Transition>
</div>
}
}