{"id":15415859,"url":"https://github.com/davidje13/react-hook-awaited","last_synced_at":"2025-03-20T13:20:18.410Z","repository":{"id":143905446,"uuid":"319136251","full_name":"davidje13/react-hook-awaited","owner":"davidje13","description":"A helper for working with asynchronous data in react functional components.","archived":false,"fork":false,"pushed_at":"2022-08-14T18:43:12.000Z","size":18,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-08T14:02:52.365Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/davidje13.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-12-06T21:34:12.000Z","updated_at":"2022-08-12T12:30:01.000Z","dependencies_parsed_at":null,"dependency_job_id":"5db7e75e-81fa-4ba5-b8ac-8739a9df5e65","html_url":"https://github.com/davidje13/react-hook-awaited","commit_stats":{"total_commits":5,"total_committers":1,"mean_commits":5.0,"dds":0.0,"last_synced_commit":"bb1d2139ddc8a7b3cf361782d5745f868df1fe29"},"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidje13%2Freact-hook-awaited","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidje13%2Freact-hook-awaited/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidje13%2Freact-hook-awaited/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/davidje13%2Freact-hook-awaited/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/davidje13","download_url":"https://codeload.github.com/davidje13/react-hook-awaited/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244618448,"owners_count":20482319,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-01T17:10:02.848Z","updated_at":"2025-03-20T13:20:18.349Z","avatar_url":"https://github.com/davidje13.png","language":"JavaScript","readme":"# React useAwaited hook\n\nA helper for working with asynchronous data in react functional components.\n\nSee the [examples](#examples) for some use cases.\n\n## Install dependency\n\n```bash\nnpm install --save react-hook-awaited\n```\n\n## Usage\n\n```jsx\nconst useAwaited = require('react-hook-awaited');\n\nconst MyComponent = () =\u003e {\n  const apiUrl = 'https://xkcd.com/info.0.json';\n  const apiResponse = useAwaited((signal) =\u003e fetch(apiUrl, { signal }).then((r) =\u003e r.json()), [apiUrl]);\n\n  switch (apiResponse.state) {\n    case 'pending':\n      return (\u003cdiv\u003eLoading...\u003c/div\u003e);\n    case 'resolved':\n      return (\u003cdiv\u003eLatest: {apiResponse.data.num}\u003c/div\u003e);\n    case 'rejected':\n      return (\n        \u003cdiv\u003e\n          Failed: {apiResponse.error}\n          \u003cbutton onClick={apiResponse.forceRefresh()}\u003eTry Again\u003c/button\u003e\n        \u003c/div\u003e\n      );\n  }\n};\n```\n\nIf you are using [eslint-plugin-react-hooks](https://www.npmjs.com/package/eslint-plugin-react-hooks),\nyou should configure it to check dependencies for `useAwaited` and\n`useAwaitedWithDefault`:\n\n```json\n\"react-hooks/exhaustive-deps\": [\"warn\", {\n  \"additionalHooks\": \"(useAwaited|useAwaitedWithDefault)\"\n}]\n```\n\nAlternatively, you can provide functions using `useCallback` yourself\n(this requires more syntax but avoids the need to reconfigure the linter):\n\n```js\nconst apiResponse = useAwaited(\n  useCallback(\n    (signal) =\u003e fetch(apiUrl, { signal }).then((r) =\u003e r.json()),\n    [apiUrl]\n  )\n);\n```\n\n## API\n\n### useAwaited(generatorFunction, deps)\n\n```javascript\nconst value = useAwaited(generatorFunction, deps);\n```\n\nInvokes the `generatorFunction` and returns the state of the returned\npromise.\n\n- `generatorFunction`: a function which returns a promise which is\n  to be awaited. It is passed a single argument: an\n  [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)\n  which will be marked as aborted if a change means that the current\n  request is no-longer required.\n- `deps`: a list of dependencies for the `generatorFunction`, matching\n  the same API as\n  [`React.useCallback`](https://reactjs.org/docs/hooks-reference.html#usecallback).\n\nThe `AbortSignal` can be passed directly to `fetch` calls to avoid\nleaving requests running which are no-longer required:\n\n```js\nuseAwaited((abortSignal) =\u003e fetch('https://example.com', { signal: abortSignal }), []);\n```\n\n**note:** If the `deps` change, the current promise will be discarded,\nthe `AbortSignal` will be triggered, `generatorFunction` will be called\nagain, and the newly returned promise will be awaited.\n\nIf you do not provide `deps`, the default is to re-invoke the generator\nwhenever the generator function changes. This means you can pass a\n`useCallback`-wrapped function _instead of_ providing `deps`.\n\n#### Return value\n\nThe response is an object which contains several properties:\n\n- `state`: one of `'pending'`, `'resolved'` or `'rejected'`. For\n  convenience these are also exported as constants `PENDING`,\n  `RESOLVED`, `REJECTED`.\n- `data`: the current data returned by the promise (if `state` is\n  `'resolved'`, otherwise `undefined`).\n- `error`: the current error returned by the promise (if `state` is\n  `'rejected'`, otherwise `undefined`).\n- `stats`: an object containing statistics about the current promise:\n  - `beginTimestamp`: time when the promise began (number of\n    milliseconds since the epoch)\n  - `endTimestamp`: time when the promise completed (number of\n    milliseconds since the epoch), or undefined if `state` is\n    `pending`.\n- `latestData`: the last successfully resolved data. Unlike `data`,\n  this continues to be available until new data replaces it.\n  This is `undefined` until the first request succeeds.\n- `latestStats`: an object containing statistics about the last\n  completed promise. Unlike `stats`, this continues to be available\n  while new data is loaded. This is `undefined` until the first\n  request has completed.\n- `forceRefresh`: a function which can be called to force an\n  immediate refresh of the data. This function is guaranteed to be\n  stable (will be the same function instance across all renders).\n\n### useAwaitedWithDefault(default, generatorFunction, deps)\n\nSame as `useAwaited`, but `latestData` will be initialised as\n`default` rather than `undefined`.\n\n## Examples\n\n### Loading data from a dynamic API endpoint\n\n```jsx\nconst useAwaited = require('react-hook-awaited');\n\nconst ComicViewer = () =\u003e {\n  const [num, setNum] = useState(1);\n  const apiUrl = `https://xkcd.com/${num}/info.0.json`;\n  const apiResponse = useAwaited((signal) =\u003e fetch(apiUrl, { signal }).then((r) =\u003e r.json()), [apiUrl]);\n\n  let content;\n  if (apiResponse.state === 'pending') {\n    content = (\u003cdiv\u003eLoading...\u003c/div\u003e);\n  } else if (apiResponse.state === 'rejected') {\n    content = (\n      \u003cdiv\u003e\n        Failed to load #{num}: {apiResponse.error}\n        \u003cbr /\u003e\n        \u003cbutton onClick={apiResponse.forceRefresh()}\u003eTry Again\u003c/button\u003e\n      \u003c/div\u003e\n    );\n  } else {\n    content = (\n      \u003cdiv\u003e\n        \u003ch1\u003e{apiResponse.data.title}\u003c/h1\u003e\n        \u003cimg src={apiResponse.data.img} alt={apiResponse.data.alt} /\u003e\n      \u003c/div\u003e\n    );\n  }\n  return (\n    \u003csection\u003e\n      \u003clabel\u003eShow XKCD \u003cinput type=\"number\" value={num} onChange={setNum} /\u003e\u003c/label\u003e\n      { content }\n    \u003c/section\u003e\n  );\n};\n```\n\n### Show latest data with user-controlled refresh\n\n```jsx\nconst useAwaited = require('react-hook-awaited');\n\nconst DataFetcher = () =\u003e {\n  const apiUrl = 'https://xkcd.com/info.0.json';\n  const apiResponse = useAwaited((signal) =\u003e fetch(apiUrl, { signal }).then((r) =\u003e r.json()), [apiUrl]);\n\n  let content = null;\n  if (apiResponse.latestData) {\n    content = (\n      \u003cdiv\u003e\n        \u003cp\u003eLatest: {apiResponse.latestData.num}\u003c/p\u003e\n        \u003cp\u003e(as of ${new Date(apiResponse.latestStats.endTimestamp).toString()})\u003c/p\u003e\n      \u003c/div\u003e\n    );\n  }\n  return (\n    \u003csection\u003e\n      {content}\n      {apiResponse.state === 'pending' ? (\n        \u003cp\u003eRefreshing...\u003c/p\u003e\n      ) : (\n        \u003cbutton onClick={apiResponse.forceRefresh()}\u003eRefresh\u003c/button\u003e\n      )}\n      {apiResponse.state === 'rejected' ? (\n        \u003cp\u003eFailed to refresh: ${apiResponse.error}\u003c/p\u003e\n      ) : null}\n    \u003c/section\u003e\n  );\n};\n```\n\n### Automatically refreshing on an interval\n\nThis also uses [react-hook-final-countdown](https://github.com/davidje13/react-hook-countdown)\n\n```jsx\nconst useAwaited = require('react-hook-awaited');\nconst {useTimeInterval} = require('react-hook-final-countdown');\n\nconst DataFetcher = () =\u003e {\n  const apiUrl = 'https://xkcd.com/info.0.json';\n  const time = useTimeInterval(1000 * 60 * 60); // update every hour\n  const apiResponse = useAwaited((signal) =\u003e fetch(apiUrl, { signal }).then((r) =\u003e r.json()), [apiUrl, time]);\n\n  return (\n    \u003csection\u003e\n      \u003cp\u003eLatest: {apiResponse.latestData?.num}\u003c/p\u003e\n      \u003cp\u003e(as of ${new Date(apiResponse.latestStats?.endTimestamp).toString()})\u003c/p\u003e\n    \u003c/section\u003e\n  );\n};\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavidje13%2Freact-hook-awaited","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdavidje13%2Freact-hook-awaited","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdavidje13%2Freact-hook-awaited/lists"}