{"id":15782460,"url":"https://github.com/dpzxsm/react-decorate-fetch","last_synced_at":"2025-03-14T09:33:05.213Z","repository":{"id":42958343,"uuid":"152845284","full_name":"dpzxsm/react-decorate-fetch","owner":"dpzxsm","description":"A library to fetch data for React Components, which has most of the similar API with react-refetch, and support Hooks","archived":false,"fork":false,"pushed_at":"2023-01-05T16:22:36.000Z","size":600,"stargazers_count":3,"open_issues_count":6,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-03-05T04:35:40.651Z","etag":null,"topics":["decorator","fetch","fetch-api","hoc","hooks","javascript","react","react-fetch-hooks","react-hooks","react-native","react-refetch","reactjs"],"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/dpzxsm.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":"SECURITY.md","support":null}},"created_at":"2018-10-13T07:06:11.000Z","updated_at":"2020-10-20T03:09:28.000Z","dependencies_parsed_at":"2023-02-04T07:16:03.500Z","dependency_job_id":null,"html_url":"https://github.com/dpzxsm/react-decorate-fetch","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dpzxsm%2Freact-decorate-fetch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dpzxsm%2Freact-decorate-fetch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dpzxsm%2Freact-decorate-fetch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dpzxsm%2Freact-decorate-fetch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dpzxsm","download_url":"https://codeload.github.com/dpzxsm/react-decorate-fetch/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243554469,"owners_count":20309934,"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":["decorator","fetch","fetch-api","hoc","hooks","javascript","react","react-fetch-hooks","react-hooks","react-native","react-refetch","reactjs"],"created_at":"2024-10-04T19:07:29.438Z","updated_at":"2025-03-14T09:33:04.793Z","avatar_url":"https://github.com/dpzxsm.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# react-decorate-fetch [![npm version](https://badge.fury.io/js/react-decorate-fetch.svg)](https://badge.fury.io/js/react-decorate-fetch)\nA library to fetch data for React Components, which has most of the similar API with [react-refetch](https://github.com/heroku/react-refetch). Different, it also supports more friendly way to use, like Hooks.\n\n## Installation\nSupporting for react and react-native, based on Fetch’s API;\n\n```sh\nnpm i react-decorate-fetch --save\nor\nyarn add react-decorate-fetch\n```\n## Why I don't use react-refetch\n`react-refetch` is a very awesome project,it  saved me a lot of time. I really like this way without setState to fetch data. Now, Hooks are growing in popularity, more projects use Hooks. So I write this library to supports Hooks, and Copy `react-refetch`’s API to compatible my old Projects.\n\n## Example\n\n```javascript\nimport { connect } from 'react-decorate-fetch';\nfunction App(props) {\n  const { userFetch } = props;\n  if(userFetch.loading){\n    return \u003cLoading /\u003e\n  }else if(userFetch.error){\n    return \u003cError /\u003e\n  }else if(userFetch.success){\n    return \u003cSuccess /\u003e\n  }\n}\nexport default connect((props) =\u003e ({\n  userFetch: `/users/detail/${props.userId}`,\n}))(App)\n```\n\n## API\n\n### Use in your Component\n#### HOC Component\n```javascript\n// use Decorator (need @babel/plugin-proposal-decorators)\n@connect(mapRequestByOptions, defaultFetchOptions, options)\nclass App extends React.Component {};\n// or not use Decorator\nApp = connect(mapRequestByOptions, defaultFetchOptions, options)(App);\n```\n\n- `connect`(mapRequestByOptions:[FetchOptions](#FetchOptions)|Function =\u003e [FetchOptions](#FetchOptions), defaultFetchOptions?:[FetchOptions](#FetchOptions), options?: Object)\n\n##### mapRequestByOptions:[FetchOptions](#FetchOptions)|Function =\u003e [FetchOptions](#FetchOptions)\nA Function to map props to [FetchOptions](#FetchOptions), if you don't need props, you can directly set FetchOptions, like:\n```javascript\nconnect({usersFetch: `/users`})\n````\n##### defaultFetchOptions:[FetchOptions](#FetchOptions)\nDefault FetchOptions for connect Component, will be Object.assign into every `FetchOptions`\n\n##### options:Object\nwithRef options to ref connect Component like `react-redux`\n\n#### React Hooks\n- `useFetch`(options:[FetchOptions](#FetchOptions), deps?: any[]);\n- `useLazyFetch`(options:[FetchOptions](#FetchOptions), deps?: any[]);\n\n##### useFetch\n```javascript\nconst APP = (props) =\u003e {\n  const fetchOptions = \"/users\";\n  const [fetchState, fetchUser] = useFetch(fetchOptions, []);\n  return \u003cdiv\u003e\n   {fetchState.loading\n        ? \u003cdiv\u003eLoading...\u003c/div\u003e\n        : fetchState.error\n          ? \u003cdiv\u003eError: {fetchState.message}\u003c/div\u003e\n          : \u003cdiv\u003eValue: {fetchState.value}\u003c/div\u003e\n      }\n    \u003cbutton onClick={() =\u003e fetchUser()}\u003eStart Fetch\u003c/button\u003e\n  \u003c/div\u003e\n}\n```\n\n##### useLazyFetch\n```javascript\nconst APP = (props) =\u003e {\n  const fetchOptions = \"/users\";\n  const fetchState = useLazyFetch(fetchOptions, []);\n  return \u003cdiv\u003e\n   {fetchState.loading\n        ? \u003cdiv\u003eLoading...\u003c/div\u003e\n        : fetchState.error\n          ? \u003cdiv\u003eError: {fetchState.message}\u003c/div\u003e\n          : \u003cdiv\u003eValue: {fetchState.value}\u003c/div\u003e\n      }\n  \u003c/div\u003e\n}\n```\n\n### Global and Middleware\nIf you want to config some Global options for all fetches, you will need some useful api to resolve it. It is not necessary, but is helpful.\n\n#### initConfig\n```javascript\ninitConfig({\n  fetchOptions: {\n    host: 'http://xxx.com',\n    headers: {}, //override default headers\n    ...otherFetchOptions\n  },\n  buildResponse: (res) =\u003e {\n     // This is default response handle, you can override it.\n     if (res \u0026\u0026 res.json) {\n       return res.json().then((dataOrError) =\u003e {\n         if (res.ok) {\n           return dataOrError;\n         } else {\n           throw dataOrError;\n         }\n       });\n     } else {\n       return {};\n     }\n  },\n  transformPostParams: (params) =\u003e {\n    // This is default transform, you can override it.\n    return JSON.stringify(params)\n  }, // transform params Option\n  fetch: require('axios') // you can replace to any you like Fetch Api's library\n})\n```\n#### applyMiddleware\n```javascript\nconst plugin = {\n  before: (context, next) =\u003e {\n    const options = context[0]; // the final fetchOptions\n    next(); // must call only once\n  },\n  after: (context, next) =\u003e {\n    const options = context[0]; // the final fetchOptions\n    let data = context[1]; // you can modify\n    next(); // must call  only once\n  }\n}\napplyMiddleware(plugin)\n// ......\n// you can add multiple plugins\n```\n\n#### removeMiddleware\n```javascript\nremoveMiddleware(plugin)\n```\n\n### Chaining Requests\nYou can set a function to [FetchOptions](#FetchOptions)'s `then`, and return a new [FetchOptions](#FetchOptions).\n\n### Mock Fetch Data\nYou can set Mock data to [FetchOptions](#FetchOptions)'s `value`,  you will receive the Mock data and no request real server.\n\n### Type Explanation\n#### FetchOptions\n`FetchOptions` based on Fetch API’s options, so you can use all Fetch API’s options, **Tips**: If FetchOptions is `string` type, will be converted to `{url: string}`, else if FetchOptions is an array, will be converted to `[FetchOptions, FetchOptions, ...]`\n\n| Property      | Type     | Description              | Require | default |\n| :------------ | :------: | :----------------------- | :-----: | :----- |\n| **url**       | String   | The Fetch API’s url, if `value` is Static, it is not required.| true | —— |\n| **method**    | String   | The Fetch API’s method | false | \"GET\" |\n| **headers**   | Object   | The Fetch API’s headers | false | { 'Accept': 'application/json', 'Content-Type': 'application/json' } |\n| **params**    | Object   | Common params for different `method`| false | {} |\n| **successText** | string   | Custom fetch success text | false | \"Success\" |\n| **refreshInterval** | number  | Interval in milliseconds to poll for new data from the URL, set 0 can stop request | false | 0 |\n| **value**     | Function\\|Any | Static response’s value or function to transform the old response’s value | false | —— |\n| **then**      | Function | [Chaining Requests](#Chaining Requests) | false | —— |\n| **delay**      | Number | Fetch delay millisecond| —— |0 | —— |\n| **cleanParams** | Boolean | Clean undefined or null params | —— | true | —— |\n| **host**      | String   | Define the host | false | —— |\n| **postForm**  | Boolean | transform params to `FormData`| false | false |\n\nSupport all other Fetch API’s options, like `body`,`mode`,`credentials`,`cache`,`redirect`,`referrer`,`referrerPolicy`,`integrity`.\n\n#### FetchState \n| Property      | Type     | Description              | default |\n| :------------ | :------: | :----------------------- | :----- |\n| **status**    | String   | One of 'pending'\\|'loading'\\|'error' |'pending' |\n| **loading**   | Boolean  | When fetching, that is true | false |\n| **error**     | Boolean  | When fetch error or throw Error, that is true | false |\n| **success**   | Boolean  | When fetch success, that is true | false |\n| **code**      | Number   | Http status code | —— |\n| **message**   | String   | `FetchOptions`’s successText or error’s message | —— |\n| **value**     | Any      | When fetch success, that is `body` | null |\n| **cancel**    | Function | If request is fetching, cancel it | () =\u003e {} |\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdpzxsm%2Freact-decorate-fetch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdpzxsm%2Freact-decorate-fetch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdpzxsm%2Freact-decorate-fetch/lists"}