Skip to content

createResource

Create a resource that fetches data asynchronously.

This function has two overloads:

  1. Simple fetcher - fetches data once when the resource is created
  2. Reactive fetcher - fetches data when a reactive source changes
import { createResource } from "@alloy-js/core";
function createResource<U>(fetcher: () => Promise<U>): Resource<U>;
fetcher() => Promise<U>

Resource<U>

// 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

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>;
refSourceRef<T> | (() => T)
fetcher(input: T) => Promise<U>

Resource<U>