This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.

yew/functional/hooks/use_transitive_state/
feat_ssr.rs

1//! The server-side rendering variant.
2
3use std::cell::RefCell;
4use std::rc::Rc;
5
6use base64ct::{Base64, Encoding};
7use serde::de::DeserializeOwned;
8use serde::Serialize;
9
10use crate::functional::{Hook, HookContext, PreparedState};
11use crate::suspense::SuspensionResult;
12
13pub(super) struct TransitiveStateBase<T, D, F>
14where
15    D: Serialize + DeserializeOwned + PartialEq + 'static,
16    T: Serialize + DeserializeOwned + 'static,
17    F: 'static + FnOnce(Rc<D>) -> T,
18{
19    pub state_fn: RefCell<Option<F>>,
20    pub deps: Rc<D>,
21}
22
23impl<T, D, F> PreparedState for TransitiveStateBase<T, D, F>
24where
25    D: Serialize + DeserializeOwned + PartialEq + 'static,
26    T: Serialize + DeserializeOwned + 'static,
27    F: 'static + FnOnce(Rc<D>) -> T,
28{
29    fn prepare(&self) -> String {
30        let f = self.state_fn.borrow_mut().take().unwrap();
31        let state = f(self.deps.clone());
32
33        let state = bincode::serialize(&(Some(&state), Some(&*self.deps)))
34            .expect("failed to prepare state");
35
36        Base64::encode_string(&state)
37    }
38}
39
40#[doc(hidden)]
41pub fn use_transitive_state<T, D, F>(
42    deps: D,
43    f: F,
44) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
45where
46    D: Serialize + DeserializeOwned + PartialEq + 'static,
47    T: Serialize + DeserializeOwned + 'static,
48    F: 'static + FnOnce(Rc<D>) -> T,
49{
50    struct HookProvider<T, D, F>
51    where
52        D: Serialize + DeserializeOwned + PartialEq + 'static,
53        T: Serialize + DeserializeOwned + 'static,
54        F: 'static + FnOnce(Rc<D>) -> T,
55    {
56        deps: D,
57        f: F,
58    }
59
60    impl<T, D, F> Hook for HookProvider<T, D, F>
61    where
62        D: Serialize + DeserializeOwned + PartialEq + 'static,
63        T: Serialize + DeserializeOwned + 'static,
64        F: 'static + FnOnce(Rc<D>) -> T,
65    {
66        type Output = SuspensionResult<Option<Rc<T>>>;
67
68        fn run(self, ctx: &mut HookContext) -> Self::Output {
69            let f = self.f;
70
71            ctx.next_prepared_state(move |_re_render, _| -> TransitiveStateBase<T, D, F> {
72                TransitiveStateBase {
73                    state_fn: Some(f).into(),
74                    deps: self.deps.into(),
75                }
76            });
77
78            Ok(None)
79        }
80    }
81
82    HookProvider::<T, D, F> { deps, f }
83}