Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Resources, Suspense and Async

Loading Data with createResource

Learn createResource in SolidJS: fetch async data, react to a source signal, read loading and error state, refetch, mutate locally and set an initial value.

Signals hold values you already have. Most apps also need values they have to wait for: a user profile from an API, search results, a file. Solid's tool for this is createResource. It turns an async function into a reactive value that knows whether it is loading, failed or ready, and it re-runs the function whenever the inputs change.

In this lesson you will create resources, tie them to a signal, read their state, and refresh or edit their data. The next lesson adds Suspense to show loading UI declaratively.

The examples use a small fakeApi function that waits with setTimeout and returns data, so every run behaves the same and needs no network. In a real app you would replace it with fetch("/api/..."), and the Solid code does not change.

The basic shape

JavaScript
import { createResource } from "solid-js";

const [user] = createResource(fetchUser);

fetchUser is any function that returns a value or a promise. createResource calls it immediately and returns a resource: a function you call like a signal (user()), plus extra properties. The result is undefined while loading.

A resource exposes:

Property Meaning
user() The latest value, or undefined if not ready
user.loading true while a request is running
user.error The error thrown by the last request, if any
user.state One of "unresolved", "pending", "ready", "refreshing", "errored"
user.latest The most recent value, kept while refreshing, without triggering Suspense (like user(), it rethrows an error)
Your first resource

Watch the state line change from pending to ready when the data arrives, and the Show swap the fallback for the content.

Using a source signal

A resource becomes powerful when you give it a source: a signal (or any function) whose value is passed to the fetcher. Whenever the source changes, the fetcher runs again.

JavaScript
const [id, setId] = createSignal(1);
const [user] = createResource(id, fetchUserById);

Rules for the source:

  • If the source returns false, null or undefined, no fetch happens and the resource stays unresolved. That makes "wait until the user types something" easy.
  • The fetcher receives the source value as its first argument, plus an info object ({ value, refetching }) as its second.
  • Each change starts a new request; Solid ignores the answers of outdated requests, so a slow old response cannot overwrite a newer one.
A resource driven by a signal

Button #4 makes the fetcher reject. The resource moves to the errored state and person.error holds the error. Note the ?.: while loading, person() is undefined.

Errors

Reading person() while the resource is in the errored state throws the error. That is deliberate: it lets an ErrorBoundary above catch it. If you want to handle errors yourself, check person.error (or person.state) first: those properties never throw.

refetch and mutate

The second element of the returned array holds two actions:

JavaScript
const [todos, { refetch, mutate }] = createResource(fetchTodos);

refetch();           // run the fetcher again with the same source
mutate((t) => [...t, newTodo]);  // replace the value locally, no request
  • refetch shows state === "refreshing" while it runs, and the old data stays visible, so lists do not flash empty.
  • mutate is for optimistic updates: change the UI immediately, then call the server. You will use it in async patterns.
refetch and mutate

Add a note on the "server", and nothing changes until you press Refetch. "Mutate locally" adds a line instantly, and the next refetch replaces it with the server's truth. The initialValue: [] option makes notes() an array from the start, so For never receives undefined, and the state starts as ready.

Fetching with real fetch

Here is the shape of a real fetcher (read-only, because the live editor is sandboxed from your API):

JavaScript
const fetchUser = async (id) => {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);  // fetch does not reject on 404
  return res.json();
};

fetch only rejects on network failure, so always check res.ok and throw, otherwise a 404 page is treated as data.

When not to use createResource

A resource is client-driven: it fetches when the component runs. In a full-stack app with routes, you usually load data through the router's query and createAsync (see route data), which also deduplicates requests and starts loading before navigation finishes. For data a component fetches on its own, such as a live search box, createResource is the right tool.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a resource's source signal do when it returns undefined?

    A falsy source (false, null or undefined) pauses fetching, which is handy for 'wait until input exists'.
  2. 2. Which property is safe to read while the resource is in an error state?

    Reading the value (or latest) rethrows the error. error and state are plain status properties.
  3. 3. What does mutate do?

    mutate writes the value directly, which is the basis of optimistic updates.
  4. 4. Why check res.ok in a fetcher?

    HTTP error statuses still resolve the promise, so you must throw yourself for the resource to enter the errored state.

Summary

  • createResource(source?, fetcher, options?) returns a resource plus { refetch, mutate }.
  • Read loading, error and state for status; the value is undefined until ready, and latest keeps the previous value while refreshing.
  • A source signal re-runs the fetcher on change and pauses it when falsy.
  • Reading an errored resource throws, so check error first or use an ErrorBoundary.
  • Use initialValue to avoid undefined, and mutate for optimistic UI.

Next: Suspense and Transitions