Nadia's Bookshop's catalogue now comes from a server, and the server takes a while to answer. While it waits, the page has to show something. If it fails, the page has to say so. If you come from React, you may be used to handling this with useEffect plus three pieces of state: data, loading, error. Solid wraps it into one.
createResource wraps an async function that fetches data (called the fetcher) and gives you two things: a reader for the data, and the status of the fetch, meaning still loading, failed, or ready. Its partner is <Suspense>, which shows a stand-in while the data hasn't arrived. It's like Nadia ordering the catalogue from the supplier by phone. While she waits, a Loading catalogue... sign goes up on the shelf. The order slip records its status: still waiting, failed, or arrived. If a customer asks for another title, Nadia calls again with the new word.
createResource and Suspense
import { createResource, Suspense, Show } from "solid-js"
const fetchData = async () => {
return { name: "Data Loaded" }
}
function App() {
const [data] = createResource(fetchData)
return (
<Suspense fallback={<p>Loading...</p>}>
<Show when={data()}>
<p>{data().name}</p>
</Show>
</Suspense>
)
}
| When | data() |
Page |
|---|---|---|
| The component runs, the fetcher is called | undefined |
Loading... |
| The promise settles | { name: "Data Loaded" } |
Data Loaded |
createResource(fetchData)callsfetchDataonce and returns[data, { refetch, mutate }].datais read like a signal:data().- Until the promise settles,
data()isundefined.<Show when={data()}>makes suredata().nameisn't read too early. <Suspense>shows itsfallbackwhile a resource read inside it isn't ready, then swaps in its contents by itself. This is the first exercise: what reads at the end isData Loaded, notLoading....
A resource's status
Besides data(), a resource has status properties. They're plain properties, read without parentheses:
| Property | Holds |
|---|---|
data.loading |
true while the fetcher hasn't finished |
data.error |
the error object if the fetcher failed |
data.state |
"unresolved" (no source yet, the fetcher has not run), "pending" (first time), "ready", "refreshing" (reloading), "errored" |
data.latest |
the last data that succeeded, kept while it reloads |
The second exercise shows those three states with <Show>, without <Suspense>:
import { createResource, Show } from "solid-js"
const fetchUser = async () => ({ name: "Andi", email: "[email protected]" })
function App() {
const [user] = createResource(fetchUser)
return (
<div>
<Show when={user.loading}><p>Loading...</p></Show>
<Show when={user.error}><p>Error!</p></Show>
<Show when={!user.error && user()}>
<p>{user().name} - {user().email}</p>
</Show>
</div>
)
}
The result is Andi - [email protected]. Why !user.error && in the third Show? A failed resource throws its error when read with user(). Tested in Solid 1.9: without that guard, a failing fetcher stops the page with Error: Server busy, though Error! was ready to show.
Source: fetch again when a signal changes
Nadia's Bookshop's catalogue following the search box. The sandbox has no network, so the "server" is a Promise that settles 800 ms later. In a real app, it would be fetch("/api/books?search=" + search).then(r => r.json()).
import { createSignal, createResource, For, Suspense } from "solid-js"
const catalog = [
{ title: "The Rainbow Troops", price: 18 },
{ title: "This Earth of Mankind", price: 24 },
{ title: "Beauty Is a Wound", price: 19 },
]
function fetchCatalog(search) {
console.log("fetcher runs, search:", JSON.stringify(search))
return new Promise(resolve => {
setTimeout(() => resolve(catalog.filter(b => b.title.toLowerCase().includes(search.toLowerCase()))), 800)
})
}
function App() {
const [search, setSearch] = createSignal("")
const [books, { refetch }] = createResource(search, fetchCatalog)
return (
<div>
<input placeholder="Search title" onInput={e => setSearch(e.target.value)} />
<button onClick={refetch}>Reload</button>
<Suspense fallback={<p>Loading catalogue...</p>}>
<ul>
<For each={books()}>{(b) => <li>{b.title} · ${b.price}</li>}</For>
</ul>
</Suspense>
</div>
)
}
createResource(search, fetchCatalog): the first argument is the source, a signal. The fetcher gets its value,fetchCatalog(""), and is called again every time the source changes: typeearth, and the console printsfetcher runs, search: "earth".- If the source is
false,nullorundefined, the fetcher isn't called. An empty string still is. refetch()calls the fetcher again with the same source, for aReloadbutton, say.
When the data reloads
This is what happens when the data reloads (you type in the search box or click Reload), tested in Solid 1.9:
Inside <Suspense> |
While reloading | Afterwards |
|---|---|---|
<For each={books()}> |
the list disappears, Loading catalogue... shows |
This Earth of Mankind · $24 |
<Show when={books.loading}><p>Updating...</p></Show> + <For each={books.latest}> |
the old list stays, plus Updating... |
This Earth of Mankind · $24 |
With books(), the Loading catalogue... sign comes back on every reload. books() read while the status is "refreshing" makes <Suspense> wait again. books.latest returns the last data without waiting, so the old list stays. The fallback only shows on the first load.
Another option: useTransition, imported from "solid-js". A source change wrapped in start(...) becomes a transition: <Suspense> keeps showing the old content until the new data is ready, and pending() is true during that time.
const [pending, start] = useTransition()
<input placeholder="Search title" onInput={e => start(() => setSearch(e.target.value))} />
<Show when={pending()}><p>Updating...</p></Show>
Tested on Solid 1.9: while earth loads, the three old books stay on screen with Updating..., then only This Earth of Mankind remains. Pick books.latest for one list with the least code. Pick useTransition when several resources in one <Suspense> must change together, or another part of the page needs to know something is loading.
When the fetcher fails
If the promise is rejected, books.state becomes "errored", books.error holds the error, and reading books() or books.latest throws that error to the nearest <ErrorBoundary>:
<ErrorBoundary fallback={(err, reset) => (
<p>Failed: {err.message} <button onClick={() => { refetch(); reset() }}>Try again</button></p>
)}>
<Suspense fallback={<p>Loading catalogue...</p>}>...</Suspense>
</ErrorBoundary>
reset() only draws its contents again, so call refetch() too, or the same error shows right back. ErrorBoundary gets its full treatment in the Error Boundaries lesson.
⚠️ A resource that throws, ignores the search, or goes back to loading
books.loading()with parentheses.loading,error,stateandlatestare properties, not functions.user.loading()stops withTypeError: user.loading is not a function. Only the resource itself is called:user().- Reading its contents before they're ready.
<p>{data().name}</p>withoutShowstops withTypeError: Cannot read properties of undefined (reading 'name'). - A signal read inside the fetcher.
createResource(() => fetchCatalog(search()))only fetches once: reads inside the fetcher aren't tracked. Make the signal the source:createResource(search, fetchCatalog). - Expecting the old list to stay. With
books()inside<Suspense>, every reload shows the fallback. Usebooks.latestwhen the old list must stay. - Grading the stand-in. The first exercise looks for
Data Loadedin a<p>, the second forAndion the page.Loading...alone doesn't pass.
TL;DR: const [data] = createResource(fetchData) calls an async fetcher and gives data() (undefined until ready) plus the properties data.loading, data.error, data.state, data.latest, read without parentheses. <Suspense fallback={...}> shows the fallback while a resource read inside it isn't ready; <Show when={data()}> guards reads of its contents. createResource(search, fetchCatalog) calls the fetcher again whenever its source changes, refetch() calls it again with the same source. On a reload, books() brings the fallback back, books.latest keeps the old data. A failed resource throws its error when read: catch it with ErrorBoundary, or guard with !user.error &&.
⚡ createResource and Suspense
Write:
const [data] = createResource(fetchData)
<Suspense fallback={<p>Loading...</p>}>
<Show when={data()}>
<p>{data().name}</p>
</Show>
</Suspense>
Meaning: createResource calls its async function once, and data() is read like a signal. Until the promise settles, data() is undefined, so Show keeps data().name from being read too early. <Suspense> shows its fallback while the data isn't ready.
⚡ Status is read without parentheses
Meaning: user.loading, user.error, user.state and user.latest are plain properties, not functions. user.loading() stops with a TypeError. Only the resource itself is called: user().
⚡ Source: fetch again when a signal changes
Write:
const [books, { refetch }] = createResource(search, fetchCatalog)
Guess first: <For each={books()}> sits inside <Suspense>. When the search is typed again, does the old list stay?
No. The list disappears and Loading catalogue... shows again on every reload. Use books.latest when the old list must stay.
Meaning: The first argument is the source, a signal. The fetcher is called again every time the source changes, and refetch() calls it again with the same source.