{"name":"suspend-react","version":"0.0.4","description":"Integrate React Suspense into your apps","main":"dist/index.cjs","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":{"fast-deep-equal":"^3.1.3"},"gitHead":"cca51dc75dcf66dbc2ab73c9a4040c0cd1c5851d","bugs":{"url":"https://github.com/pmndrs/suspend-react/issues"},"_id":"suspend-react@0.0.4","_nodeVersion":"17.0.1","_npmVersion":"8.1.0","dist":{"integrity":"sha512-xKQGfLp2VglOeEtC/rShRPUtI34EaTfVcgnh4RPjrrcin7QKNiZhx7nFfImNxfJwC5VrrOqHQrZ2YVA7t0EboA==","shasum":"b1f1b0228363a0b667d217f92f22d93575ba5a1e","tarball":"http://registry-npm.ywwl.com/suspend-react/download/suspend-react-0.0.4.tgz","fileCount":12,"unpackedSize":25121,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDyz6F9kCTt81zXiOKjwHQKy7ihRt7ZohxAcZ+GlXxRIAiBaxUHS5vvu/JDSo+fTsh3Ehe++fW+8ob7Z2pxvLmaOLQ=="}],"size":8946,"noattachment":false,"key":"/suspend-react/-/suspend-react-0.0.4.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.4_1635894002167_0.3683988145834127"},"_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":1635894002551,"_cnpm_publish_time":1635894002551,"dist-tags":{"latest":"0.1.3"}}