Files
Devour/devour_data/docs/create-resource.json
T
Tomas Dvorak 898a3c303f update
2026-02-24 10:33:59 +01:00

17 lines
8.3 KiB
JSON

{
"id": "559b56f9cca55d8e9ffb7895",
"source": "solid:signals",
"type": "github-document",
"title": "create-resource",
"content": "---\ntitle: createResource\nuse_cases: \u003e-\n data fetching, api calls, async operations, loading states, error handling,\n server data, suspense boundaries\ntags:\n - async\n - fetching\n - api\n - suspense\n - loading\n - error-handling\n - ssr\nversion: \"1.0\"\ndescription: \u003e-\n Fetch async data with createResource. Handles loading states, errors, and\n integrates with Suspense for seamless data fetching in Solid.js applications.\n---\n\nCreates a reactive resource that manages asynchronous data fetching and loading states, automatically tracking dependencies and providing a simple interface for reading, refreshing, and error handling.\nIt integrates with Solid's reactivity system and Suspense boundaries.\n\n## Import\n\n```typescript\nimport { createResource } from \"solid-js\";\n```\n\n## Type\n\n```typescript\n// Without source\nfunction createResource\u003cT, R = unknown\u003e(\n\tfetcher: ResourceFetcher\u003ctrue, T, R\u003e,\n\toptions?: ResourceOptions\u003cT\u003e\n): ResourceReturn\u003cT, R\u003e;\n\n// With source\nfunction createResource\u003cT, S, R = unknown\u003e(\n\tsource: ResourceSource\u003cS\u003e,\n\tfetcher: ResourceFetcher\u003cS, T, R\u003e,\n\toptions?: ResourceOptions\u003cT, S\u003e\n): ResourceReturn\u003cT, R\u003e;\n```\n\n### Related types\n\n```typescript\ntype ResourceReturn\u003cT, R = unknown\u003e = [Resource\u003cT\u003e, ResourceActions\u003cT, R\u003e];\n\ntype Resource\u003cT\u003e = {\n\t(): T | undefined;\n\tstate: \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\tloading: boolean;\n\terror: any;\n\tlatest: T | undefined;\n};\n\ntype ResourceActions\u003cT, R = unknown\u003e = {\n\tmutate: (value: T | undefined) =\u003e T | undefined;\n\trefetch: (info?: R) =\u003e Promise\u003cT\u003e | T | undefined;\n};\n\ntype ResourceSource\u003cS\u003e =\n\t| S\n\t| false\n\t| null\n\t| undefined\n\t| (() =\u003e S | false | null | undefined);\n\ntype ResourceFetcher\u003cS, T, R = unknown\u003e = (\n\tsource: S,\n\tinfo: { value: T | undefined; refetching: R | boolean }\n) =\u003e T | Promise\u003cT\u003e;\n\ninterface ResourceOptions\u003cT, S = unknown\u003e {\n\tinitialValue?: T;\n\tname?: string;\n\tdeferStream?: boolean;\n\tssrLoadFrom?: \"initial\" | \"server\";\n\tstorage?: (\n\t\tinit: T | undefined\n\t) =\u003e [Accessor\u003cT | undefined\u003e, Setter\u003cT | undefined\u003e];\n\tonHydrated?: (k: S | undefined, info: { value: T | undefined }) =\u003e void;\n}\n```\n\n## Parameters\n\n### `source`\n\n- **Type:** `ResourceSource\u003cS\u003e`\n- **Default:** `undefined`\n\nReactive data source evaluated before the fetcher runs.\nWhen the value is `undefined`, `null`, or `false`, the fetcher is not called.\nOtherwise the current value is passed as the first fetcher argument.\nEach change triggers the fetcher again.\n\n### `fetcher`\n\n- **Type:** `ResourceFetcher\u003cS, T, R\u003e`\n\nFunction that receives the source value (or `true` if no source), the current resource info, and returns a value or Promise.\n\n### `options`\n\n- **Type:** `ResourceOptions\u003cT, S\u003e`\n- **Default:** `{}`\n\nConfiguration options for the resource.\n\n#### `initialValue`\n\n- **Type:** `T`\n- **Default:** `undefined`\n\nInitial value for the resource.\nWhen provided, the resource starts in \"ready\" state and the type excludes `undefined`.\n\n#### `name`\n\n- **Type:** `string`\n- **Default:** `undefined`\n\nA name for debugging purposes in development mode.\n\n#### `deferStream`\n\n- **Type:** `boolean`\n- **Default:** `false`\n\nControls streaming behavior during server-side rendering.\n\n#### `ssrLoadFrom`\n\n- **Type:** `\"initial\" | \"server\"`\n- **Default:** `\"server\"`\n\nDetermines how the resource loads during SSR hydration.\n\n- \"server\": Uses the server-fetched value during hydration.\n- \"initial\": Re-fetches on the client after hydration.\n\n#### `storage`\n\n- **Type:** `(init: T | undefined) =\u003e [Accessor\u003cT | undefined\u003e, Setter\u003cT | undefined\u003e]`\n- **Default:** `createSignal`\n\nCustom storage function for the resource value, useful for persistence or custom state management.\n\n#### `onHydrated`\n\n- **Type:** `(k: S | undefined, info: { value: T | undefined }) =\u003e void`\n- **Default:** `undefined`\n\nCallback fired when the resource hydrates on the client side.\n\n## Return value\n\n- **Type:** `[Resource\u003cT\u003e, ResourceActions\u003cT, R\u003e]`\n\nReturns a tuple containing the resource accessor and resource actions.\n\n### `Resource`\n\n```typescript\ntype Resource\u003cT\u003e = {\n\t(): T | undefined;\n\tstate: \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\tloading: boolean;\n\terror: any;\n\tlatest: T | undefined;\n};\n```\n\n- `state`: Current state of the resource.\n See the table below for state descriptions.\n- `loading`: Indicates if the resource is currently loading.\n- `error`: Error information if the resource failed to load.\n- `latest`: The latest value of the resource.\n\n| State | Description | Loading | Error | Latest |\n| ------------ | --------------------------------------- | ------- | ----------- | ----------- |\n| `unresolved` | Initial state, not yet fetched | `false` | `undefined` | `undefined` |\n| `pending` | Fetching in progress | `true` | `undefined` | `undefined` |\n| `ready` | Successfully fetched | `false` | `undefined` | `T` |\n| `refreshing` | Refetching while keeping previous value | `true` | `undefined` | `T` |\n| `errored` | Fetching failed | `false` | `any` | `undefined` |\n\n### `ResourceActions`\n\n```typescript\ntype ResourceActions\u003cT, R = unknown\u003e = {\n\tmutate: (value: T | undefined) =\u003e T | undefined;\n\trefetch: (info?: R) =\u003e Promise\u003cT\u003e | T | undefined;\n};\n```\n\n- `mutate`: Function to manually overwrite the resource value without calling the fetcher.\n Allows you to optimistically update the resource value locally, without making a network request.\n- `refetch`: Function to re-run the fetcher without changing the source.\n If a parameter is provided to `refetch`, it will be passed to the fetcher's `refetching` property.\n\n## Examples\n\n### Basic usage\n\n```typescript\nconst [data] = createResource(async () =\u003e {\n\tconst response = await fetch(\"/api/data\");\n\treturn response.json();\n});\n\n// Access data\nconsole.log(data()); // undefined initially, then fetched data\nconsole.log(data.loading); // true during fetch\nconsole.log(data.state); // \"pending\" → \"ready\"\n```\n\n### With source\n\n```typescript\nconst [userId, setUserId] = createSignal(1);\n\nconst [user] = createResource(userId, async (id) =\u003e {\n\tconst response = await fetch(`/api/users/${id}`);\n\treturn response.json();\n});\n\n// Automatically refetches when userId changes\nsetUserId(2);\n```\n\n### With actions\n\n```typescript\nconst [posts, { refetch, mutate }] = createResource(fetchPosts);\n\n// Manual refetch\nawait refetch();\n\n// Optimistic update\nmutate((posts) =\u003e [...posts, newPost]);\n```\n\n### Error handling\n\n```typescript\nconst [data] = createResource(async () =\u003e {\n const response = await fetch('/api/data');\n if (!response.ok) throw new Error('Failed to fetch');\n return response.json();\n});\n\n// In JSX\n\u003cErrorBoundary fallback={\u003cdiv\u003eError loading data\u003c/div\u003e}\u003e\n \u003cdiv\u003e{data()?.title}\u003c/div\u003e\n\u003c/ErrorBoundary\u003e\n```\n\n### With initial value\n\n```typescript\nconst [user] = createResource(() =\u003e fetchUser(), {\n\tinitialValue: { name: \"Loading...\", id: 0 },\n});\n\n// user() is never undefined\nconsole.log(user().name); // \"Loading...\" initially\n```",
"url": "https://github.com/solidjs/solid-docs/blob/HEAD/src/routes/reference/basic-reactivity/create-resource.mdx",
"metadata": {
"path": "src/routes/reference/basic-reactivity/create-resource.mdx",
"repo": "solidjs/solid-docs",
"repo_url": "https://github.com/solidjs/solid-docs.git",
"size": 7057,
"source_type": "github"
},
"hash": "4035a5101272775e723bcd794cbd3853ec74e2060529dc3e8538f29c8d95820c",
"timestamp": "2026-02-23T11:43:00.188516595+01:00"
}