forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
use_sleep.rs
40 lines (32 loc) · 811 Bytes
/
use_sleep.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
use std::rc::Rc;
use std::time::Duration;
use gloo_timers::future::sleep;
use yew::prelude::*;
use yew::suspense::{Suspension, SuspensionResult};
#[derive(PartialEq)]
pub struct SleepState {
s: Suspension,
}
impl SleepState {
fn new() -> Self {
let s = Suspension::from_future(async {
sleep(Duration::from_secs(5)).await;
});
Self { s }
}
}
impl Reducible for SleepState {
type Action = ();
fn reduce(self: Rc<Self>, _action: Self::Action) -> Rc<Self> {
Self::new().into()
}
}
#[hook]
pub fn use_sleep() -> SuspensionResult<Rc<dyn Fn()>> {
let sleep_state = use_reducer(SleepState::new);
if sleep_state.s.resumed() {
Ok(Rc::new(move || sleep_state.dispatch(())))
} else {
Err(sleep_state.s.clone())
}
}