Function leptos::create_local_resource

source ·
pub fn create_local_resource<S, T, Fu>(
    source: impl Fn() -> S + 'static,
    fetcher: impl Fn(S) -> Fu + 'static
) -> Resource<S, T>
where S: PartialEq + Clone + 'static, T: 'static, Fu: Future<Output = T> + 'static,
Expand description

Creates a local Resource, which is a signal that reflects the current state of an asynchronous task, allowing you to integrate async Futures into the synchronous reactive system.

Takes a fetcher function that generates a Future when called and a source signal that provides the argument for the fetcher. Whenever the value of the source changes, a new Future will be created and run.

Unlike create_resource(), this Future is always run on the local system and therefore its result type does not need to be Serializable.

Local resources do not load on the server, only in the client’s browser.

§When to use a Local Resource

create_resource has three different features:

  1. gives a synchronous API for asynchronous things
  2. integrates with Suspense/`Transition``
  3. makes your application faster by starting things like DB access or an API request on the server, rather than waiting until you’ve fully loaded the client

create_local_resource is useful when you can’t or don’t need to do #3 (serializing data from server to client), but still want #1 (synchronous API for async) and #2 (integration with Suspense).

#[derive(Debug, Clone)] // doesn't implement Serialize, Deserialize
struct ComplicatedUnserializableStruct {
    // something here that can't be serialized
}

// an async function whose results can't be serialized from the server to the client
// (for example, opening a connection to the user's device camera)
async fn setup_complicated_struct() -> ComplicatedUnserializableStruct {
    // do some work
    ComplicatedUnserializableStruct {}
}

// create the resource; it will run but not be serialized
let result =
    create_local_resource(move || (), |_| setup_complicated_struct());