{"id":23186085,"url":"https://github.com/termosa/use-defer","last_synced_at":"2025-04-05T04:44:56.933Z","repository":{"id":57388021,"uuid":"312751343","full_name":"termosa/use-defer","owner":"termosa","description":"Simplify work with async functions with memoization and state","archived":false,"fork":false,"pushed_at":"2021-08-16T17:37:18.000Z","size":1342,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-11T23:16:18.981Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/termosa.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-11-14T05:18:16.000Z","updated_at":"2021-08-16T17:37:21.000Z","dependencies_parsed_at":"2022-09-06T08:11:42.707Z","dependency_job_id":null,"html_url":"https://github.com/termosa/use-defer","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/termosa%2Fuse-defer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/termosa%2Fuse-defer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/termosa%2Fuse-defer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/termosa%2Fuse-defer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/termosa","download_url":"https://codeload.github.com/termosa/use-defer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247289400,"owners_count":20914464,"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-12-18T10:14:26.207Z","updated_at":"2025-04-05T04:44:56.909Z","avatar_url":"https://github.com/termosa.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# use-defer\n\n\u003e Simplify work with async functions with memoization and state\n\n[![NPM](https://img.shields.io/npm/v/use-defer.svg)](https://www.npmjs.com/package/use-defer) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)\n\n## Install\n\n```bash\nnpm install --save use-defer\n```\n\n## Usage\n\n```tsx\nimport * as React from 'react'\n\nimport useDefer, { Status } from 'use-defer'\n// Or: import { useDefer, Status } from 'use-defer'\n\nconst Example = () =\u003e {\n  const {\n    execute, // Callback for the [asyncFunction] with the same arguments list and result\n    status,  // One of: Status.IDLE - no request, Status.PENDING - waiting for results, Status.SUCCESS \u0026 Status.ERROR\n    value,   // Result of the last request\n    error,   // Error thrown during the execution of the last request\n  } = useDefer(\n    asyncFunction, // The function that returns a [Promise] instance\n    [],            // Optional list of [React.DependencyList] type to update [asyncFunction]\n    [],            // Optional arguments list. The [asyncFunction] will be called immediately if this is set\n  );\n\n  // ...\n};\n```\n\n## Examples\n\n### Using it for a single async function\n\n[Source code](https://github.com/termosa/use-defer/blob/master/example/src/SingleFunctionExample.js)\n\n```tsx\nconst generateNumber = max =\u003e new Promise((resolve, reject) =\u003e {\n  if (max \u003e 0) setTimeout(resolve, 2e3, Math.round(Math.random() * max));\n  else setTimeout(reject, 2e3, 'Max value must be greater than zero');\n});\n\nconst defaultMax = 100;\n\nconst SingleFunctionExample = () =\u003e {\n  const [max, setMax] = React.useState('');\n\n  const { value, error, status } = useDefer(\n    generateNumber,           // Async function that returns promise\n    [max],                    // Dependencies\n    [max ? +max : defaultMax] // Initial arguments\n  );\n\n  return (\n    \u003cdiv\u003e\n      \u003cdiv\u003e\n        \u003cinput\n          type=\"number\"\n          value={max}\n          placeholder={defaultMax.toString()}\n          onChange={e =\u003e setMax(e.target.value)}\n        /\u003e\n        {status === 'pending' ? \u003cspan\u003eprocessing \u003c/span\u003e : null}\n      \u003c/div\u003e\n      {value !== undefined ? \u003cdiv\u003eLast result: {value}\u003c/div\u003e : null}\n      {error ? \u003cdiv\u003eError: {error}\u003c/div\u003e : null}\n    \u003c/div\u003e\n  );\n};\n```\n\n### Create a model hook with auto reloading\n\n[Source code](https://github.com/termosa/use-defer/blob/master/example/src/MultipleFunctionsExample.js)\n\n```tsx\nconst useResources = () =\u003e {\n  const { execute: reload, value: resources, status } = useDefer(api.get, [], []);\n  const { execute: create } = useDefer(resource =\u003e api.post(resource).then(reload));\n  const { execute: remove } = useDefer(id =\u003e api.delete(id).then(reload));\n\n  return { resources, status, create, remove };\n};\n\nconst MultipleFunctionsExample = () =\u003e {\n  const resourceLabelRef = useRef(null);\n  const { resources, status, create, remove } = useResources();\n\n  const onSubmit = e =\u003e {\n    e.preventDefault();\n    create({ label: resourceLabelRef.current.value });\n    resourceLabelRef.current.value = '';\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cform onSubmit={onSubmit}\u003e\n        \u003cinput type=\"text\" ref={resourceLabelRef} required /\u003e\n        \u003cinput type=\"submit\" value=\"Add\" /\u003e\n      \u003c/form\u003e\n\n      {!resources \u0026\u0026 status === 'pending' ? \u003cp\u003eLoading...\u003c/p\u003e : null}\n\n      {resources\n        ? \u003col\u003e\n          {resources.map(res =\u003e (\n            \u003cli key={res.id}\u003e\n              {res.label}\n              {' '}\n              \u003cinput type=\"button\" onClick={() =\u003e remove(res.id)} value=\"remove\" /\u003e\n            \u003c/li\u003e\n          ))}\n        \u003c/ol\u003e\n        : null\n      }\n    \u003c/div\u003e\n  );\n};\n```\n\n## License\n\nMIT © [termosa](https://github.com/termosa)\n\n---\n\nThis hook is created using [create-react-hook](https://github.com/hermanya/create-react-hook).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftermosa%2Fuse-defer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftermosa%2Fuse-defer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftermosa%2Fuse-defer/lists"}