Skip to main content

use_future

Function use_future 

Source
pub fn use_future<D: 'static, F: Future<Output = D> + 'static>(
    future: impl FnMut() -> F + 'static,
) -> FutureTask<D, F>
Expand description

Create a FutureTask with the given callback.

This is a hook around spawn that exposes the progress of the future as reactive state, so you can render the pending, loading and fulfilled cases without managing the task by hand. It starts polling automatically.

#[derive(PartialEq)]
struct Greeting;

impl Component for Greeting {
    fn render(&self) -> impl IntoElement {
        let future = use_future(|| async {
            // Some async work...
            "Hello!".to_string()
        });

        match &*future.state() {
            FutureState::Pending | FutureState::Loading => "Loading...".to_string(),
            FutureState::Fulfilled(text) => text.clone(),
        }
    }
}

The callback is reactive, any State read inside of it (outside the async block) subscribes the future, restarting it when that state changes. Reads inside the async block do not subscribe.

let user_id = use_state(|| 1);

// Restarts whenever `user_id` changes.
let user = use_future(move || {
    let user_id = user_id();
    async move { load_user(user_id).await }
});

To read its state use FutureTask::state. You may restart/stop it using FutureTask::start and FutureTask::cancel.