{"name":"suspend-react","version":"0.0.10","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","husky":{"hooks":{"pre-commit":"lint-staged"}},"lint-staged":{"*.{js,jsx,ts,tsx}":["eslint --fix"]},"scripts":{"build":"rollup -c","postbuild":"tsc --emitDeclarationOnly","prepublishOnly":"npm run build","test":"echo no tests yet"},"devDependencies":{"@babel/core":"7.16.0","@babel/plugin-proposal-class-properties":"^7.16.0","@babel/plugin-transform-modules-commonjs":"7.16.0","@babel/plugin-transform-parameters":"7.16.0","@babel/plugin-transform-runtime":"7.16.0","@babel/plugin-transform-template-literals":"7.16.0","@babel/preset-env":"7.16.0","@babel/preset-react":"7.16.0","@babel/preset-typescript":"^7.16.0","@rollup/plugin-babel":"^5.3.0","@rollup/plugin-node-resolve":"^13.0.6","@types/jest":"^27.0.2","@types/node":"^16.11.6","@types/react":"^17.0.33","@types/react-dom":"^17.0.10","@types/react-test-renderer":"^17.0.1","@typescript-eslint/eslint-plugin":"^5.3.0","@typescript-eslint/parser":"^5.3.0","eslint":"^8.1.0","eslint-config-prettier":"^8.3.0","eslint-import-resolver-alias":"^1.1.2","eslint-plugin-import":"^2.25.2","eslint-plugin-jest":"^25.2.2","eslint-plugin-prettier":"^4.0.0","eslint-plugin-react":"^7.26.1","eslint-plugin-react-hooks":"^4.2.0","husky":"^7.0.4","lint-staged":"^11.2.6","prettier":"^2.4.1","react":"^17.0.1","rollup":"^2.59.0","rollup-plugin-size-snapshot":"^0.12.0","rollup-plugin-terser":"^7.0.2","typescript":"^4.4.4"},"peerDependencies":{"react":">=17.0"},"dependencies":{},"gitHead":"ccf74fc5d009b3c61d72b9ea66e63dadcd1e36a5","bugs":{"url":"https://github.com/pmndrs/suspend-react/issues"},"_id":"suspend-react@0.0.10","_nodeVersion":"18.6.0","_npmVersion":"8.13.2","dist":{"integrity":"sha512-7yyJ1aBr9Ap4XZQOBaYlOelNcRc42zv50C0pVNOHfhW/DwTbHGFVZKKJsVndyQvQTv/fAkIO9TAMvGiSCjT0Zw==","shasum":"9b1cc83d13e0ded81fd6f65a3d564bbbfa7024ab","tarball":"http://registry-npm.ywwl.com/suspend-react/download/suspend-react-0.0.10.tgz","fileCount":13,"unpackedSize":30938,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQCg0yB6meoMkjgdAEzGctQLwhrRNQ3+9EXoykRRmAiw8AIhALxXCU53xhcrgtd8tdfOMfhiELxAapcM5tfH4z2SlUce"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkVK33ACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqOZA/9F4iD0WpBGeRw0W3nuxoRmPUVqCVm/Xv8V55WqwN8jD4y84kX\r\nDHuNHiL4gseXaIDkMZiD38t0jOqlw5Rpo5v3lkZNFVWSihtRzZAXI80c4voK\r\nTwtYJ4ecCvS4a0pgaH3xnY73CcMRii75NjzppbstB24qoNXvW17abKWelYbu\r\nDV5CKDP1HInOF+dUpQV43RGOh7tAnSlPu91gFb5ZZO3wM9Bfo0N35xV+4mb1\r\nHN3XYxa9rCZ7t+bGvi7NBtb/GUYwL3YPWVxyXfo7bpX41ELwyZVZc/4CzacS\r\nzb/mrKivTyk/uCOt9V6a+FT/yskO+vq+6LnzOX71FO8c4FuCt9ejo/xYBM79\r\n6HKTf2aQL0Ze3rtrBu6T+eIAlxLXBx5xSf3k20lwPXLWMnoNjfc0q2YS8erG\r\ngl5QPFtdng/ymK5yVqZjv3L3iWsDv1LFj5K2wWYHAsR8+lIjCkL6cV40J//U\r\ngTmnQ88N5v0wAgc9w0Lf6Znq0Ypv/OKLYaUWk2i+mPpUVwjBlP9tNZR8fts6\r\nMsmgVAmYypGHFVzrSBtWWr8KQD80009mutOvyzKJdnHle5RIysjnWY4yOuB/\r\nYp2290cJ1eGqRgAwfPg8YQa4JYe/Q0tAUXcpT3gCnQ9davnmn+imUk4RCL8q\r\nMin7CKgf2H4CcL69/ivv8weQyCc227KHOK8=\r\n=SG5C\r\n-----END PGP SIGNATURE-----\r\n","size":10620,"noattachment":false,"key":"/suspend-react/-/suspend-react-0.0.10.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.0.10_1683271159327_0.600133421763722"},"_hasShrinkwrap":false,"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":1683271159608,"_cnpm_publish_time":1683271159608,"dist-tags":{"latest":"0.1.3"}}