createResource
Edit this pageSolid 2.0 —
createResource has been removed in Solid 2.0. Async is now a first-class capability of computations. Use createMemo with an async function and wrap reads in <Loading> boundaries.
Replacement: async computations + Loading
In Solid 2.0, any computation may return a Promise. Consumers read the accessor as usual; if the value isn't ready, the graph suspends and <Loading> displays fallback UI.
Basic data fetching
// 1.xconst [data, { mutate, refetch }] = createResource(source, fetchData)
// 2.0import { createMemo } from "solid-js"
const data = createMemo(() => fetchData(source()))Loading states
// 1.x<Suspense fallback={<Spinner />}> <UserProfile /></Suspense>
// 2.0<Loading fallback={<Spinner />}> <UserProfile /></Loading>Checking loading state
// 1.xdata.loading
// 2.0import { isPending } from "solid-js"
// false during initial Loading fallback, true during revalidationisPending(() => data())Getting the latest value
// 1.xdata.latest
// 2.0import { latest } from "solid-js"
latest(() => data())Mutations and refetching
// 1.xconst [data, { mutate, refetch }] = createResource(fetchTodos)mutate(optimisticValue)refetch()
// 2.0import { action, refresh } from "solid-js"import { createStore, createOptimisticStore, snapshot } from "solid-js/store"
const [todos] = createStore(() => api.getTodos(), { list: [] })const [optimisticTodos, setOptimisticTodos] = createOptimisticStore( () => snapshot(todos), { list: [] })
const addTodo = action(function* (todo) { setOptimisticTodos((s) => s.list.push(todo)) // optimistic yield api.addTodo(todo) // async work refresh(todos) // refresh reads})Error handling
// 1.xdata.error
// 2.0<Errored fallback={(err, reset) => <span>Error: {err.message}</span>}> <Loading fallback={<Spinner />}> <div>{data()}</div> </Loading></Errored>Migration summary
| 1.x | 2.0 |
|---|---|
createResource(fetcher) | createMemo(() => fetcher()) |
createResource(source, fetcher) | createMemo(() => fetcher(source())) |
data.loading | isPending(() => data()) |
data.latest | latest(() => data()) |
data.error | <Errored> boundary |
<Suspense> | <Loading> |
mutate | createOptimistic / createOptimisticStore |
refetch | refresh() |
See also
- Fetching data guide — Complete guide to data fetching in Solid 2.0
createMemo— Async memos that suspendLoading— Async boundary componentErrored— Error boundary componentisPending— Stale-while-revalidating indicatoraction— Mutation wrapper