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

Macro use_prepared_state

Source
use_prepared_state!() { /* proc-macro */ }
Expand description

Use a state prepared on the server side and its value is sent to the client side during hydration.

The component sees the same value on the server side and client side if the component is hydrated.

It accepts a closure as the first argument and a dependency type as the second argument. It returns SuspensionResult<Option<Rc<T>>>.

During hydration, it will only return Ok(Some(Rc<T>)) if the component is hydrated from a server-side rendering artifact and its dependency value matches.

let state = use_prepared_state!(|deps| -> ReturnType { ... }, deps)?;

It has the following signature:

use yew::prelude::*;
use yew::suspense::SuspensionResult;

#[hook]
pub fn use_prepared_state<T, D, F>(deps: D, f: F) -> SuspensionResult<Option<Rc<T>>>
where
    D: Serialize + DeserializeOwned + PartialEq + 'static,
    T: Serialize + DeserializeOwned + 'static,
    F: FnOnce(Rc<D>) -> T,

The first argument can also be an async closure.

let state = use_prepared_state!(async |deps| -> ReturnType { ... }, deps)?;

When accepting an async closure, it has the following signature:

use yew::prelude::*;
use yew::suspense::SuspensionResult;

#[hook]
pub fn use_prepared_state<T, D, F, U>(
        deps: D,
        f: F,
    ) -> SuspensionResult<Option<Rc<T>>>
    where
        D: Serialize + DeserializeOwned + PartialEq + 'static,
        T: Serialize + DeserializeOwned + 'static,
        F: FnOnce(Rc<D>) -> U,
        U: 'static + Future<Output = T>,

During server-side rendering, a value of type T will be calculated from the first closure.

If the bundle is compiled without server-side rendering, the closure will be stripped automatically.

ยงNote

You MUST denote the return type of the closure with |deps| -> ReturnType { ... }. This type is used during client side rendering to deserialize the state prepared on the server side.

Whilst async closure is an unstable feature, the procedural macro will rewrite this to a closure that returns an async block automatically. You can use this hook with async closure in stable Rust.