use super::{use_ref, RefContainer};
use crate::react_bindings;
use js_sys::Function;
use std::cell::Ref;
use wasm_bindgen::{JsValue, 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
.call0(&JsValue::NULL)
.expect_throw("unable to call state update");
}
}
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,
}
}