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 | () => Promise<U> |
Returns
Section titled “Returns”Resource<U>
Examples
Section titled “Examples”// Simple usage - fetches data once when created
const userResource = createResource(async () => {
const response = await fetch('/api/user');
return response.json();
});
// Access the resource state
console.log(userResource.loading); // true initially
console.log(userResource.data); // null initially
console.log(userResource.error); // null initially
// Reactive usage - fetches data when the ref changes
const 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 changes
userId.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 | Ref<T> | (() => T) | |
| fetcher | (input: T) => Promise<U> |
Returns
Section titled “Returns”Resource<U>