pub fn use_server_future<T, F>(
future: impl FnMut() -> F + 'static,
) -> Result<Resource<T>, RenderError>Expand description
Runs a future and returns a result with a resource if the future is finished or a suspended error if it is still running. The future may run on the server during hydration.
- When compiled as server, the closure’s future is ran to completion and the resulting data is serialized on the server and sent to the client.
- When compiled as web client, the data is deserialized from the server if already available, otherwise runs on the client. Data is usually only available if this hook exists in a component during hydration.
- When otherwise compiled, the closure is run directly with no serialization.
On the server, this will wait until the future is resolved before continuing to render. Thus, this blocks other subsequent server hooks. The result is cached.
Unlike use_resource dependencies are only tracked inside the function that spawns the async block, not the async block itself.
// ❌ The future inside of use_server_future is not reactive
let id = use_signal(|| 0);
use_server_future(move || {
async move {
// But the future is not reactive which means that the future will not subscribe to any reads here
println!("{id}");
}
});
// ✅ The closure that creates the future for use_server_future is reactive
let id = use_signal(|| 0);
use_server_future(move || {
// The closure itself is reactive which means the future will subscribe to any signals you read here
let cloned_id = id();
async move {
// But the future is not reactive which means that the future will not subscribe to any reads here
println!("{cloned_id}");
}
});§Example
use dioxus::prelude::*;
fn App() -> Element {
let mut article_id = use_signal(|| 0);
// `use_server_future` will spawn a task that runs on the server and serializes the result to send to the client.
// The future will rerun any time the
// Since we bubble up the suspense with `?`, the server will wait for the future to resolve before rendering
let article = use_server_future(move || fetch_article(article_id()))?;
rsx! {
"{article().unwrap()}"
}
}