-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
use_state.rs
116 lines (105 loc) · 3.36 KB
/
use_state.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
109
110
111
112
113
114
115
116
mod common;
use common::obtain_result;
use wasm_bindgen_test::*;
use yew::functional::{
use_effect_with_deps, use_state, use_state_eq, FunctionComponent, FunctionProvider,
};
use yew::{html, Html};
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn use_state_works() {
struct UseStateFunction {}
impl FunctionProvider for UseStateFunction {
type TProps = ();
fn run(_: &Self::TProps) -> Html {
let counter = use_state(|| 0);
if *counter < 5 {
counter.set(*counter + 1)
}
return html! {
<div>
{"Test Output: "}
<div id="result">{*counter}</div>
{"\n"}
</div>
};
}
}
type UseComponent = FunctionComponent<UseStateFunction>;
yew::start_app_in_element::<UseComponent>(
gloo_utils::document().get_element_by_id("output").unwrap(),
);
let result = obtain_result();
assert_eq!(result.as_str(), "5");
}
#[wasm_bindgen_test]
fn multiple_use_state_setters() {
struct UseStateFunction {}
impl FunctionProvider for UseStateFunction {
type TProps = ();
fn run(_: &Self::TProps) -> Html {
let counter = use_state(|| 0);
let counter_clone = counter.clone();
use_effect_with_deps(
move |_| {
// 1st location
counter_clone.set(*counter_clone + 1);
|| {}
},
(),
);
let another_scope = {
let counter = counter.clone();
move || {
if *counter < 11 {
// 2nd location
counter.set(*counter + 10)
}
}
};
another_scope();
return html! {
<div>
{ "Test Output: " }
// expected output
<div id="result">{ *counter }</div>
{ "\n" }
</div>
};
}
}
type UseComponent = FunctionComponent<UseStateFunction>;
yew::start_app_in_element::<UseComponent>(
gloo_utils::document().get_element_by_id("output").unwrap(),
);
let result = obtain_result();
assert_eq!(result.as_str(), "11");
}
#[wasm_bindgen_test]
fn use_state_eq_works() {
use std::sync::atomic::{AtomicUsize, Ordering};
static RENDER_COUNT: AtomicUsize = AtomicUsize::new(0);
struct UseStateFunction {}
impl FunctionProvider for UseStateFunction {
type TProps = ();
fn run(_: &Self::TProps) -> Html {
RENDER_COUNT.fetch_add(1, Ordering::Relaxed);
let counter = use_state_eq(|| 0);
counter.set(1);
return html! {
<div>
{"Test Output: "}
<div id="result">{*counter}</div>
{"\n"}
</div>
};
}
}
type UseComponent = FunctionComponent<UseStateFunction>;
yew::start_app_in_element::<UseComponent>(
gloo_utils::document().get_element_by_id("output").unwrap(),
);
let result = obtain_result();
assert_eq!(result.as_str(), "1");
assert_eq!(RENDER_COUNT.load(Ordering::Relaxed), 2);
}