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
use super::{use_ref, RefContainer};
use crate::{
callback::{Callable, Void},
react_bindings, Persisted, PersistedOrigin,
};
use js_sys::Function;
use std::cell::Ref;
use wasm_bindgen::UnwrapThrowExt;
#[derive(Debug)]
pub struct State<T> {
ref_container: RefContainer<Option<T>>,
update: Function,
}
impl<T: 'static> State<T> {
pub fn value(&self) -> Ref<'_, T> {
Ref::map(self.ref_container.current(), |x| {
x.as_ref().expect_throw("no state value available")
})
}
pub fn set(&mut self, mutator: impl FnOnce(T) -> T) {
let value = self.ref_container.current_mut().take();
let new_value = value.map(|value| mutator(value));
self.ref_container.set_current(new_value);
self
.update
.call(&Void.into())
.expect_throw("unable to call state update");
}
}
impl<T: 'static> Persisted for State<T> {
fn ptr(&self) -> PersistedOrigin {
self.ref_container.ptr()
}
}
impl<T> Clone for State<T> {
fn clone(&self) -> Self {
Self {
ref_container: self.ref_container.clone(),
update: self.update.clone(),
}
}
}
pub fn use_state<T: 'static>(init: impl FnOnce() -> T) -> State<T> {
let mut ref_container = use_ref(None);
if ref_container.current().is_none() {
ref_container.set_current(Some(init()));
}
let update = react_bindings::use_rust_state();
State {
ref_container,
update,
}
}