createResource
Overload 1
Section titled “Overload 1”Create a resource that fetches data asynchronously.
This function has two overloads:
- Simple fetcher - fetches data once when the resource is created
- Reactive fetcher - fetches data when a reactive source changes
import { createResource } from "@alloy-js/core";
function createResource<U>(fetcher: () => Promise<U>): Resource<U>;
Parameters
Section titled “Parameters”fetcher |
|
Returns
Section titled “Returns”Resource<U>
Examples
Section titled “Examples”// Simple usage - fetches data once when createdconst userResource = createResource(async () => { const response = await fetch('/api/user'); return response.json();});
// Access the resource stateconsole.log(userResource.loading); // true initiallyconsole.log(userResource.data); // null initiallyconsole.log(userResource.error); // null initially
// Reactive usage - fetches data when the ref changesconst userId = ref(1);
const userResource = createResource(userId, async (id) => { const response = await fetch(`/api/user/${id}`); return response.json();});
// The fetcher will be called automatically when userId changesuserId.value = 2; // This triggers a new fetch with id=2
Overload 2
Section titled “Overload 2”Create a resource that fetches data asynchronously based on a reactive source.
import { createResource } from "@alloy-js/core";
function createResource<T, U>(refSource: Ref<T> | (() => T), fetcher: (input: T) => Promise<U>): Resource<U>;
Parameters
Section titled “Parameters”refSource |
|
fetcher |
|
Returns
Section titled “Returns”Resource<U>