{"id":13450493,"url":"https://github.com/schettino/react-request-hook","last_synced_at":"2025-03-23T16:31:29.386Z","repository":{"id":34079528,"uuid":"168860972","full_name":"schettino/react-request-hook","owner":"schettino","description":"🧘Managed, cancelable and safely typed requests.","archived":false,"fork":false,"pushed_at":"2022-12-09T13:56:46.000Z","size":3162,"stargazers_count":114,"open_issues_count":51,"forks_count":6,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-22T01:04:20.507Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","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/schettino.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":"2019-02-02T18:01:04.000Z","updated_at":"2025-02-19T18:47:43.000Z","dependencies_parsed_at":"2022-08-17T20:50:52.493Z","dependency_job_id":null,"html_url":"https://github.com/schettino/react-request-hook","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/schettino%2Freact-request-hook","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/schettino%2Freact-request-hook/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/schettino%2Freact-request-hook/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/schettino%2Freact-request-hook/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/schettino","download_url":"https://codeload.github.com/schettino/react-request-hook/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244890091,"owners_count":20527033,"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-07-31T07:00:35.204Z","updated_at":"2025-03-23T16:31:28.982Z","avatar_url":"https://github.com/schettino.png","language":"TypeScript","funding_links":[],"categories":["Packages"],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg width=\"600\" src=\"https://raw.githubusercontent.com/schettino/react-request-hook/master/other/react-request-hook.png\"\u003e\n\u003c/p\u003e\n\n\u003e Managed, cancelable and safely typed requests.\n\n\u003c!-- prettier-ignore-start --\u003e\n[![NPM][npm-badge]][npm]\n[![Build Status][build-badge]][build]\n[![Code Coverage][coverage-badge]][coverage]\n[![Bundle Size][bundle-size-badge]][bundle-size]\n[![PRs Welcome][prs-badge]][prs]\n[![MIT License][license-badge]][license]\n\n[![Edit react-request-hook-examples](https://codesandbox.io/static/img/play-codesandbox.svg)][codesandbox]\n\n\u003c!-- prettier-ignore-end --\u003e\n\n## Table of Contents\n\n- [Install](#install)\n- [Quick Start](#quick-start)\n- [Usage](#usage)\n  - [`useResource`](#useresource)\n  - [`useRequest`](#userequest)\n  - [`request()`](#request)\n  - [`createRequestError()`](#createrequesterror)\n- [Type safety for non typescript projects](#type-safety-for-non-typescript-projects)\n- [Examples](#examples)\n- [Acknowledgement](#acknowledgement)\n- [License](#license)\n\n## Install\n\n```bash\n# Yarn\nyarn add react-request-hook axios\n\n# NPM\nnpm install --save react-request-hook axios\n```\n\n## Quick Start\n\n```jsx\nimport {RequestProvider} from 'react-request-hook';\nimport axios from 'axios';\n\n// More info about configuration: https://github.com/axios/axios#axioscreateconfig\nconst axiosInstance = axios.create({\n  baseURL: 'https://example.com/',\n});\n\nReactDOM.render(\n  \u003cRequestProvider value={axiosInstance}\u003e\n    \u003cApp /\u003e\n  \u003c/RequestProvider\u003e,\n  document.getElementById('root'),\n);\n```\n\n```jsx\n// User Profile component\nfunction UserProfile(props) {\n  const [profile, getProfile] = useResource(id =\u003e ({\n    url: `/user/${id}`,\n    method: 'GET'\n  }))\n\n  useEffect(() =\u003e getProfile(props.userId), [])\n\n  if(profile.isLoading) return \u003cSpinner /\u003e\n\n  return (\n    \u003cProfileScreen\n      avatar={profile.data.avatar}\n      email={profile.data.email}\n      name={profile.data.name} /\u003e\n  )\n}\n```\n\n## Usage\n\n### useResource\n\nThe `useResource` hook manages the request state under the hood. Its high-level API allows one request to be made at a time. Subsequent requests cancel the previous ones, leaving the call to be made with the most recent data available. The API is intended to be similar to `useState` and `useEffect`.\n\nIt requires a function as the first argument that is just a [request config][axios-request-config] factory and returns a tuple with the resource state and a function to trigger the request call, which accepts the same arguments as the factory one.\n\n```tsx\nconst [comments, getComments] = useResource(id =\u003e ({\n  url: `/post/${id}/comments`,\n  method: 'get',\n}));\n```\n\nThe request function returns a canceler that allows you to easily cancel a request on a cleaning phase of a hook.\n\n```tsx\nuseEffect(() =\u003e {\n  if (props.isDialogOpen) {\n    return getComments(props.postId);\n  }\n}, [props.isDialogOpen]);\n```\n\n```tsx\ninterface Resource {\n  isLoading: boolean;\n\n  // same as `response.data` resolved from the axios promise\n  data: Payload\u003cRequest\u003e | null;\n\n  // Shortcut function to cancel a pending request\n  cancel: (message?: string) =\u003e void;\n\n  // normalized error\n  error: RequestError | null;\n}\n```\n\nThe request can also be triggered passing its arguments as dependencies to the _useResource_ hook.\n\n```tsx\nconst [comments] = useResource(\n  (id: string) =\u003e ({\n    url: `/post/${id}/comments`,\n    method: 'get',\n  }),\n  [props.postId],\n);\n```\n\nIt has the same behavior as `useEffect`. Changing those values triggers another request and cancels the previous one if it's still pending.\n\nIf you want more control over the request calls or the ability to call multiple requests from the same resource or not at the same time, you can rely on the **useRequest** hook.\n\n### useRequest\n\nThis hook is used internally by **useResource**. It's responsible for creating the request function and manage the cancel tokens that are being created on each of its calls. This hook also normalizes the error response (if any) and provides a helper that cancel all pending request.\n\nIt accepts the same function signature as `useResource` (a function that returns an object with the Axios request config).\n\n```tsx\nconst [request, createRequest] = useRequest((id: string) =\u003e ({\n  url: `/post/${id}/comments`,\n  method: 'get',\n}));\n```\n\n```tsx\ninterface CreateRequest {\n  // same args used on the callback provided to the hook\n  (...args): {\n    // cancel the requests created on this factory\n    cancel: (message?: string) =\u003e void;\n\n    ready: () =\u003e Promise;\n  };\n}\n\ninterface Request {\n  hasPending: boolean;\n\n  // clear all pending requests\n  clear: (message?: string) =\u003e void;\n}\n```\n\nBy using it, you're responsible for handling the promise resolution. It's still canceling pending requests when unmounting the component.\n\n```tsx\nuseEffect(() =\u003e {\n  const {ready, cancel} = createRequest(props.postId);\n  ready()\n    .then(setState)\n    .catch(error =\u003e {\n      if (error.isCancel === false) {\n        setError(error);\n      }\n    });\n  return cancel;\n}, [props.postId]);\n```\n\n### request\n\nThe `request` function allows you to define the response type coming from it. It also helps with creating a good pattern on defining your API calls and the expected results. It's just an identity function that accepts the request config and returns it. Both `useRequest` and `useResource` extract the expected and annotated type definition and resolve it on the `response.data` field.\n\n```tsx\nconst api = {\n  getUsers: () =\u003e {\n    return request\u003cUsers\u003e({\n      url: '/users',\n      method: 'GET',\n    });\n  },\n\n  getUserPosts: (userId: string) =\u003e {\n    return request\u003cPosts\u003e({\n      url: `/users/${userId}/posts`,\n      method: 'GET',\n    });\n  },\n};\n```\n\n### createRequestError\n\nThe `createRequestError` normalizes the error response. This function is used internally as well. The `isCancel` flag is returned, so you don't have to call **axios.isCancel** later on the promise catch block.\n\n```tsx\ninterface RequestError {\n  // same as `response.data`, where response is the object coming from the axios promise\n  data: Payload\u003cRequest\u003e;\n\n  message: Error['message'];\n\n  // code on the `data` field, `error.code` or `error.response.status`\n  // in the order\n  code: number | string;\n}\n```\n\n## Type safety for non typescript projects\n\nThis library is entirely written in typescript, so depending on your editor you might have all the type hints out of the box. However, we also provide a payload field to be attached to the request config object, which allows you to define and use the typings for the payload of a given request. We believe that this motivates a better and clean code as we're dealing with some of the most substantial parts of our app implementation.\n\n```js\nconst api = {\n  getUsers: () =\u003e {\n    return {\n      url: '/users',\n      method: 'GET',\n      payload: [{\n        id: String(),\n        age: Number(),\n        likesVideoGame: Boolean(),\n      }],\n    });\n  },\n};\n```\n\nAnd you'll have\n\n\u003cp align=\"center\"\u003e\n  \u003cimg width=\"600\" src=\"https://raw.githubusercontent.com/schettino/react-request-hook/master/other/type-hint.png\"\u003e\n\u003c/p\u003e\n\n## Example\n\nYou can try out react-request-hook right in your browser with the [Codesandbox example][codesandbox].\n\nThe example folder contains a `/components` folder with different use cases, like infinite scrolling components, search input that triggers the API, and so on. It's currently a work in progress.\n\n## Acknowledgement\n\nThanks to @kentcdodds for making this implementation a lot easier to test. [create-react-library](https://www.npmjs.com/package/create-react-library) for the initial setup and [Grommet](https://github.com/grommet/grommet) with its great components used in the examples.\n\n## License\n\nMIT\n\n\u003c!-- prettier-ignore-start --\u003e\n\n[axios-request-config]: (https://github.com/axios/axios#request-config)\n[npm]: https://www.npmjs.com/package/react-request-hook\n[npm-badge]: https://img.shields.io/npm/v/react-request-hook.svg\n[node]: https://nodejs.org\n[build-badge]: https://img.shields.io/travis/schettino/react-request-hook.svg?style=flat-square\n[build]: https://travis-ci.org/schettino/react-request-hook\n[coverage-badge]: https://img.shields.io/codecov/c/github/schettino/react-request-hook.svg?style=flat-square\n[coverage]: https://codecov.io/github/schettino/react-request-hook\n[license-badge]: https://img.shields.io/npm/l/react-testing-library.svg?style=flat-square\n[license]: https://github.com/kentcdodds/react-testing-library/blob/master/LICENSE\n[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square\n[prs]: http://makeapullrequest.com\n[bundle-size]: https://bundlephobia.com/result?p=react-request-hook@latest\n[bundle-size-badge]: https://badgen.net/bundlephobia/minzip/react-request-hook@latest\n[codesandbox]: https://codesandbox.io/s/github/schettino/react-request-hook-examples/tree/master/?fontsize=14\u0026view=preview\n\n\u003c!-- prettier-ignore-end --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fschettino%2Freact-request-hook","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fschettino%2Freact-request-hook","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fschettino%2Freact-request-hook/lists"}