Function use_server_future

Source
pub fn use_server_future<T, F>(
    future: impl FnMut() -> F + 'static,
) -> Result<Resource<T>, RenderError>
where T: Serialize + DeserializeOwned + 'static, F: Future<Output = T> + 'static,
Expand description

Runs a future with a manual list of dependencies and returns a resource with the result if the future is finished or a suspended error if it is still running.

On the server, this will wait until the future is resolved before continuing to render. When the future is resolved, the result will be serialized into the page and hydrated on the client without rerunning the future.

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()}"
    }
}