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

17 lines
6.3 KiB
JSON

{
"id": "ddb677f6b517a0ef90c1e7c6",
"source": "solid:signals",
"type": "github-document",
"title": "cache",
"content": "---\ntitle: cache\nisDeprecated: true\nuse_cases: \u003e-\n api calls, data fetching, deduplication, preloading routes, caching responses,\n preventing waterfalls\ntags:\n - cache\n - deprecated\n - data-fetching\n - deduplication\n - preload\nversion: '1.0'\ndescription: \u003e-\n Deprecated caching API for deduplicating requests and preloading data. Use\n query instead for better performance and invalidation.\n---\n\n:::caution[Deprecation Warning]\nThis API is deprecated since `v0.15.0` of Solid Router. Use [query](/solid-router/reference/data-apis/query) instead. It will be removed in an upcoming release.\n:::\n\n`cache` is a [higher-order function](https://en.wikipedia.org/wiki/Higher-order_function) designed to create a new function with the same signature as the function passed to it.\nWhen this newly created function is called for the first time with a specific set of arguments, the original function is run, and its return value is stored in a cache and returned to the caller of the created function.\nThe next time the created function is called with the same arguments (as long as the cache is still valid), it will return the cached value instead of re-executing the original function.\n\n:::note\n`cache` can be defined anywhere and then used inside your components with [`createAsync`](/solid-router/reference/data-apis/create-async).\n\nHowever, using `cache` directly in [`createResource`](/reference/basic-reactivity/create-resource) will not work since the fetcher is not reactive and will not invalidate properly.\n\n:::\n\n## Usage\n\n```js\nconst getUser = query(\n\t(id, options = {}) =\u003e\n\t\tfetch(`/api/users/${id}?summary=${options.summary || false}`).then((r) =\u003e\n\t\t\tr.json()\n\t\t),\n\t\"usersById\"\n);\n\ngetUser(123); // Causes a GET request to /api/users/123?summary=false\ngetUser(123); // Does not cause a GET request\ngetUser(123, { summary: true }); // Causes a GET request to /api/users/123?summary=true\nsetTimeout(() =\u003e getUser(123, { summary: true }), 999000); // Eventually causes another GET request to /api/users/123?summary=true\n```\n\n### With preload functions\n\nUsing it with a [preload function](/solid-router/reference/preload-functions/preload):\n\n```js\nimport { lazy } from \"solid-js\";\nimport { Route } from \"@solidjs/router\";\nimport { getUser } from ... // the cache function\n\nconst User = lazy(() =\u003e import(\"./pages/users/[id].js\"));\n\n// preload function\nfunction preloadUser({params, location}) {\n void getUser(params.id)\n}\n\n// Pass it in the route definition\n\u003cRoute path=\"/users/:id\" component={User} preload={preloadUser} /\u003e;\n```\n\n### Inside a route's component\n\nUsing it inside a route's component:\n\n```jsx\n// pages/users/[id].js\nimport { getUser } from ... // the cache function\n\nexport default function User(props) {\n const user = createAsync(() =\u003e getUser(props.params.id));\n return \u003ch1\u003e{user().name}\u003c/h1\u003e;\n}\n```\n\n## Cache function capabilities\n\n`cache` accomplishes the following:\n\n1. Deduping on the server for the lifetime of the request.\n2. Preloading the cache in the browser - this lasts 5 seconds.\n When a route is preloaded on hover or when preload is called when entering a route it will make sure to dedupe calls.\n3. A reactive refetch mechanism based on key.\n This prevents routes that are not new from retriggering on action revalidation.\n4. Serve as a back/forward cache for browser navigation for up to 5 minutes.\n Any user based navigation or link click bypasses it.\n Upon revalidation or new fetch the cache is updated.\n\n## Cache keys\n\nTo ensure that the cache keys are consistent and unique, arguments are deterministically serialized using JSON.stringify.\nBefore serialization, key/value pairs in objects are sorted so that the order of properties does not affect the serialization.\nFor instance, both `{ name: 'Ryan', awesome: true }` and `{ awesome: true, name: 'Ryan' }` will serialize to the same string so that they produce the same cache key.\n\n## Return value\n\nThe return value is a `CachedFunction`, a function that has the same signature as the function you passed to `cache`.\nThis cached function stores the return value using the cache key.\nUnder most circumstances, this temporarily prevents the passed function from running with the same arguments, even if the created function is called repeatedly.\n\n## Arguments\n\n| argument | type | description |\n| -------- | ----------------------- | ------------------------------------------------------------------------- |\n| `fn` | `(...args: any) =\u003e any` | A function whose return value you'd like to be cached. |\n| `name`\\* | string | Any arbitrary string that you'd like to use as the rest of the cache key. |\n\n\\*Since the internal cache is shared by all the functions using `cache`, the string should be unique for each function passed to `cache`.\nIf the same key is used with multiple functions, one function might return the cached result of the other.\n\n## Methods\n\n### `.key` and `.keyFor`\n\nCached functions provide `.key` and `.keyFor`, are useful when retrieving the keys used in cases involving invalidation:\n\n```ts\nlet id = 5;\ngetUser.key; // returns \"users\"\ngetUser.keyFor(id); // returns \"users[5]\"\n```\n\n### `revalidate`\n\nThe cache can be revalidated using the `revalidate` method or the `revalidate` keys that are set on the response from the actions.\nIf the entire key is passed, it will invalidate all entries for the cache (ie. `users` in the example above).\nIf only a single entry needs to be invalidated, `keyFor` is provided.\nTo revalidate everything in the cache, pass `undefined` as the key.",
"url": "https://github.com/solidjs/solid-docs/blob/HEAD/src/routes/solid-router/reference/data-apis/cache.mdx",
"metadata": {
"path": "src/routes/solid-router/reference/data-apis/cache.mdx",
"repo": "solidjs/solid-docs",
"repo_url": "https://github.com/solidjs/solid-docs.git",
"size": 5630,
"source_type": "github"
},
"hash": "df93f9befb49e69c89e4d9e800e09d903a370a993d1d9e7bf1e26016534d538a",
"timestamp": "2026-02-23T11:43:00.192605881+01:00"
}