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::serde::encode_to_vec(
34            (Some(&state), Some(&*self.deps)),
35            bincode::config::standard(),
36        )
37        .expect("failed to prepare state");
38
39        Base64::encode_string(&state)
40    }
41}
42
43#[doc(hidden)]
44pub fn use_transitive_state<T, D, F>(
45    deps: D,
46    f: F,
47) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
48where
49    D: Serialize + DeserializeOwned + PartialEq + 'static,
50    T: Serialize + DeserializeOwned + 'static,
51    F: 'static + FnOnce(Rc<D>) -> T,
52{
53    struct HookProvider<T, D, F>
54    where
55        D: Serialize + DeserializeOwned + PartialEq + 'static,
56        T: Serialize + DeserializeOwned + 'static,
57        F: 'static + FnOnce(Rc<D>) -> T,
58    {
59        deps: D,
60        f: F,
61    }
62
63    impl<T, D, F> Hook for HookProvider<T, D, F>
64    where
65        D: Serialize + DeserializeOwned + PartialEq + 'static,
66        T: Serialize + DeserializeOwned + 'static,
67        F: 'static + FnOnce(Rc<D>) -> T,
68    {
69        type Output = SuspensionResult<Option<Rc<T>>>;
70
71        fn run(self, ctx: &mut HookContext) -> Self::Output {
72            let f = self.f;
73
74            ctx.next_prepared_state(move |_re_render, _| -> TransitiveStateBase<T, D, F> {
75                TransitiveStateBase {
76                    state_fn: Some(f).into(),
77                    deps: self.deps.into(),
78                }
79            });
80
81            Ok(None)
82        }
83    }
84
85    HookProvider::<T, D, F> { deps, f }
86}