resource
Reactive async data fetching with caching and mutation.
/** * Create a reactive resource for async data fetching. * @param fetcher Async function to fetch data, receives key as argument. * @param options Options for key, initialData, cacheTime, onSuccess, onError, etc. * @returns Resource object with loading, error, data, refetch, reset, mutate, abort, etc. */resource<T, K>( fetcher: (key: K) => Promise<T>, options?: { key?: () => K, initialData?: T, cacheTime?: number, onSuccess?: (data: T) => void, onError?: (err: any) => void }): { loading: () => boolean, error: () => any, data: () => T | undefined, refetch: () => void, reset: () => void, mutate: (updater: () => Promise<T>) => Promise<void>, invalidate: () => void}
Create a reactive resource for async data. The resource tracks loading, error, and data states, and can be refetched, reset, mutated, or invalidated. Useful for fetching data that depends on reactive keys and integrates with signal and effect.
import { signal, effect } from "@hellajs/core";import { resource } from "@hellajs/resource";
// Reactive key for fetching userconst userId = signal("1");
// Create a resource for user dataconst userResource = resource( (id: string) => fetch(`/api/user/${id}`).then(r => r.json()), { key: () => userId(), initialData: null, cacheTime: 60000, // 1 minute cache onSuccess: (data) => console.log("Loaded", data), onError: (err) => console.error("Error", err) });
effect(() => { if (userResource.loading()) console.log("Loading..."); if (userResource.error()) console.error(userResource.error()); if (userResource.data()) console.log("User:", userResource.data());});
// Refetch, reset, mutate, invalidateuserResource.refetch();userResource.reset();userResource.mutate(async () => { // Optimistic update return { id: userId(), name: "New Name" };});userResource.invalidate();