wasm_react/hooks/
use_deferred_value.rs

1use super::{use_ref, RefContainer};
2use crate::react_bindings;
3use std::cell::Ref;
4use wasm_bindgen::UnwrapThrowExt;
5
6/// Allows access to the underlying deferred value persisted with
7/// [`use_deferred_value()`].
8#[derive(Debug)]
9pub struct DeferredValue<T>(RefContainer<Option<(T, u8)>>);
10
11impl<T: 'static> DeferredValue<T> {
12  /// Returns a reference to the underlying deferred value.
13  pub fn value(&self) -> Ref<'_, T> {
14    Ref::map(self.0.current(), |x| {
15      &x.as_ref().expect_throw("no deferred value available").0
16    })
17  }
18}
19
20impl<T> Clone for DeferredValue<T> {
21  fn clone(&self) -> Self {
22    Self(self.0.clone())
23  }
24}
25
26/// Returns the given value, or in case of urgent updates, returns the previous
27/// value given.
28pub fn use_deferred_value<T: 'static>(value: T) -> DeferredValue<T> {
29  let mut ref_container = use_ref(None::<(T, u8)>);
30
31  let deferred_counter = react_bindings::use_deferred_value(
32    ref_container
33      .current()
34      .as_ref()
35      .map(|current| current.1.wrapping_add(1))
36      .unwrap_or(0),
37  );
38
39  if Some(deferred_counter)
40    != ref_container.current().as_ref().map(|current| current.1)
41  {
42    // Deferred value changed
43    ref_container.set_current(Some((value, deferred_counter)));
44  }
45
46  DeferredValue(ref_container)
47}