{"name":"suspend-react","version":"0.1.2","description":"Integrate React Suspense into your apps","main":"dist/index.cjs.js","module":"dist/index.js","types":"dist/index.d.ts","sideEffects":false,"keywords":["react","suspense","resource","asset"],"author":{"name":"Paul Henschel"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/pmndrs/suspend-react.git"},"homepage":"https://github.com/pmndrs/suspend-react#readme","peerDependencies":{"react":">=17.0"},"dependencies":{},"private":false,"gitHead":"dd041193c571f7d685f2017aa6f37858590fec3e","bugs":{"url":"https://github.com/pmndrs/suspend-react/issues"},"_id":"suspend-react@0.1.2","_nodeVersion":"18.16.0","_npmVersion":"9.7.1","dist":{"integrity":"sha512-FcaK2hEC1BxKodWzkGZBvqE7oNeY4ZjFjVeLMBQdhVisjgbyk5HV9JiEvXyM4pimT5JDn6DorCF6wHWC1qW+CA==","shasum":"4223c7ebd75013623594786276711bc018085c5c","tarball":"http://registry-npm.ywwl.com/suspend-react/download/suspend-react-0.1.2.tgz","fileCount":6,"unpackedSize":13348,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQD/3mJxUfmZTjvThIpgOijCt8zaDt/gxUjVAt8BJ4HM3wIgR8aenWyX8dniVrpmSFzjU/C7/x2YD9By6QLl5eEvl8o="}],"size":4551,"noattachment":false,"key":"/suspend-react/-/suspend-react-0.1.2.tgz"},"_npmUser":{"name":"drcmda","email":"drcmda@gmail.com"},"directories":{},"maintainers":[{"name":"drcmda","email":"drcmda@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/suspend-react_0.1.2_1686650835226_0.49520141630924175"},"_hasShrinkwrap":false,"deprecated":"This version has issue running in cjs environment.","readme":"[![Build Size](https://img.shields.io/bundlephobia/minzip/suspend-react@0.0.8?label=bundle%20size&style=flat&colorA=000000&colorB=000000)](https://bundlephobia.com/result?p=suspend-react)\n[![Version](https://img.shields.io/npm/v/suspend-react?style=flat&colorA=000000&colorB=000000)](https://www.npmjs.com/package/suspend-react)\n\n<br />\n<a href=\"https://github.com/pmndrs/suspend-react\"><img src=\"https://github.com/pmndrs/suspend-react/blob/main/hero.svg?raw=true\" /></a>\n<br />\n<br />\n\n```shell\nnpm install suspend-react\n```\n\nThis library integrates your async ops into React suspense. Pending- and error-states are handled at the parental level which frees the individual component from that burden and allows for better orchestration. Think of it as async/await for components. **Works in all React versions >= 16.6**.\n\n```jsx\nimport { Suspense } from 'react'\nimport { suspend } from 'suspend-react'\n\nfunction Post({ id, version }) {\n  const data = suspend(async () => {\n    const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)\n    return res.json()    \n  }, [id, version])\n  return (\n    <div>\n      {data.title} by {data.by}\n    </div>\n  )\n}\n\nfunction App() {\n  return (\n    <Suspense fallback={<div>loading...</div>}>\n      <Post id={1000} version=\"v0\" />\n    </Suspense>\n  )\n}\n```\n\n#### API\n\n```tsx\nconst suspend = <Keys extends Tuple<unknown>, Fn extends (...keys: Keys) => Promise<unknown>>(\n  fn: Fn | Promise<unknown>,\n  keys?: Keys,\n  config?: Config\n) => Await<ReturnType<Fn>>\n```\n\n```tsx\n// Function that returns a promise\nconst result = suspend((...keys) => anyPromise, keys, config)\n// async function\nconst result = suspend(async (...keys) => { /* ... */ }, keys, config)\n// Promise with keys\nconst result = suspend(anyPromise, keys, config)\n// Promise itself is the key\nconst result = suspend(anyPromise)\n```\n\n`suspend` yields control back to React and the render-phase is aborted. It will resume once your promise resolves. For this to work you need to wrap it into a `<React.Suspense>` block, which requires you to set a fallback (can be `null`).\n\nThe dependencies (the 2nd argument) act as cache-keys, use as many as you want. If an entry is already in cache, calling `suspend` with the same keys will return it _immediately_ without breaking the render-phase. Cache access is similar to useMemo but *across the component tree*.\n\nThe 1st argument has to be a promise, or a function that returns a promise, or an asyn function. It receives the keys as arguments. `suspend` will return the resolved value, not a promise! This is guaranteed, *you do not have to check for validity*. Errors will bubble up to the nearest error-boundary.\n\n#### Config\n\nBoth `suspend` and `preload` can _optionally_ receive a config object,\n\n###### Keep-alive\n\nThe `lifespan` prop allows you to invalidate items over time, it defaults to `0` (keep-alive forever). Every read refreshes the timer to ensure that used entries stay valid.\n\n```jsx\n// Keep cached item alive for one minute without read\nsuspend(fn, keys, { lifespan: 60000 })\n```\n\n###### Equality function\n\nThe `equal` prop customizes per-key validation, it defaults to `(a, b) => a === b` (reference equality).\n\n```jsx\nimport equal from 'fast-deep-equal'\n\n// Validate keys deeply\nsuspend(fn, keys, { equal })\n```\n\n#### Preloading\n\n```jsx\nimport { preload } from 'suspend-react'\n\nasync function fetchFromHN(id, version) {\n  const res = await fetch(`https://hacker-news.firebaseio.com/${version}/item/${id}.json`)\n  return res.json()\n}\n\npreload(fetchFromHN, [1000, 'v0'])\n```\n\n#### Cache busting\n\n```jsx\nimport { clear } from 'suspend-react'\n\n// Clear all cached entries\nclear()\n// Clear a specific entry\nclear([1000, 'v0'])\n```\n\n#### Peeking into entries outside of suspense\n\n```jsx\nimport { peek } from 'suspend-react'\n\n// This will either return the value (without suspense!) or undefined\npeek([1000, 'v0'])\n```\n\n#### Making cache-keys unique\n\nSince `suspend` operates on a global cache (for now, see [React 18](#react-18)), you might be wondering if keys could bleed, and yes they would. To establish cache-safety, create unique or semi-unique appendixes.\n\n```diff\n- suspend(fn, [1000, 'v0'])\n+ suspend(fn, [1000, 'v0', 'functionName/fetch'])\n```\n\nIf you publish a library that suspends, consider symbols.\n\n```jsx\nconst fetchUUID = Symbol()\n\nexport function Foo() {\n  suspend(fn, [1000, 'v0', fetchUUID])\n```\n\n#### Typescript\n\nCorrect types will be inferred automatically.\n\n#### React 18\n\nSuspense, as is, has been a stable part of React since 16.6, but React will likely add some [interesting caching and cache busting APIs](https://github.com/reactwg/react-18/discussions/25) that could allow you to define cache boundaries declaratively. Expect these to be work for suspend-react once they come out.\n\n#### Demos\n\nFetching posts from hacker-news: [codesandbox](https://codesandbox.io/s/use-asset-forked-yb62q)\n\nInfinite list: [codesandbox](https://codesandbox.io/s/use-asset-infinite-list-forked-cwvs7)\n","publish_time":1686650835449,"_cnpm_publish_time":1686650835449,"dist-tags":{"latest":"0.1.3"}}