react-fetch-hook
Advanced tools
Comparing version 1.3.2 to 1.3.3
@@ -14,3 +14,3 @@ "use strict"; | ||
function useFetch(path, options) { | ||
function useFetch(path, options, specialOptions) { | ||
var defaultFormatter = function defaultFormatter(response) { | ||
@@ -25,3 +25,3 @@ if (!response.ok) { | ||
var fetchInstance = function fetchInstance(formatter) { | ||
return function (path, options) { | ||
return function (path, options, specialOptions) { | ||
var _ref = options || {}, | ||
@@ -32,3 +32,5 @@ depends = _ref.depends, | ||
var _preventCallFetch = depends ? depends.reduce(function (accumulator, currentValue) { | ||
var _depends = specialOptions && specialOptions.depends || depends; | ||
var _preventCallFetch = _depends ? _depends.reduce(function (accumulator, currentValue) { | ||
return accumulator || !currentValue; | ||
@@ -49,3 +51,3 @@ }, false) : preventCallFetch; | ||
return (0, _usePromise.usePromise)(fetchInstance(formatter), path, fetchOptions); | ||
return (0, _usePromise.usePromise)(fetchInstance(formatter), path, fetchOptions, specialOptions); | ||
} else { | ||
@@ -52,0 +54,0 @@ return (0, _usePromise.usePromise)(fetchInstance(), path); |
{ | ||
"name": "react-fetch-hook", | ||
"version": "1.3.2", | ||
"version": "1.3.3", | ||
"description": "React fetch hook", | ||
@@ -5,0 +5,0 @@ "main": "./dist/index.js", |
111
README.md
@@ -7,22 +7,4 @@ # react-fetch-hook | ||
React hook, which allows you to conveniently work with *fetch*. Good Flow support. | ||
React hook for conveniently use Fetch API. | ||
## Installation | ||
Install it with yarn: | ||
``` | ||
yarn add react-fetch-hook | ||
``` | ||
Or with npm: | ||
``` | ||
npm i react-fetch-hook --save | ||
``` | ||
## Usage | ||
*useFetch* hook accepts the same arguments as *fetch* function. | ||
```javascript | ||
@@ -44,16 +26,52 @@ import React from "react"; | ||
You can pass any *fetch* options: | ||
*useFetch* accepts the same arguments as *fetch* function. | ||
## Installation | ||
Install it with yarn: | ||
``` | ||
yarn add react-fetch-hook | ||
``` | ||
Or with npm: | ||
``` | ||
npm i react-fetch-hook --save | ||
``` | ||
## API | ||
### `useFetch` | ||
Create a hook wrapper for `fetch` call. | ||
```javascript | ||
const { isLoading, data } = useFetch("https://swapi.co/api/people/1", { | ||
method: "get", | ||
headers: { | ||
Accept: "application/json, application/xml, text/plain, text/html, *.*", | ||
"Content-Type": "application/json; charset=utf-8" | ||
useFetch( | ||
path: RequestInfo, | ||
options?: { | ||
...RequestOptions, | ||
formatter?: Response => Promise | ||
depends?: Array<boolean> | ||
}, | ||
specialOptions?: { | ||
depends?: Array<boolean> | ||
} | ||
}); | ||
): TUseFetchResult | ||
``` | ||
### Custom formatter | ||
You can pass *formatter* prop for using custom formatter function. Default is used *response => response.json()* formatter. | ||
where `TUseFetchResult` is: | ||
```javascript | ||
{ | ||
data: any, | ||
isLoading: boolean, | ||
error: any | ||
} | ||
``` | ||
#### Options: | ||
##### RequestInfo, RequestOptions | ||
`RequestInfo`, `RequestOptions` is [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) args. | ||
##### formatter | ||
`formatter` - optional formatter function. | ||
Default is `response => response.json()` formatter. | ||
Example: | ||
```javascript | ||
const { isLoading, data } = useFetch("https://swapi.co/api/people/1", { | ||
@@ -64,5 +82,6 @@ formatter: (response) => response.text() | ||
``` | ||
### Prevent call `fetch` | ||
For prevent call fetch you can pass *depends* prop: | ||
##### depends | ||
The request will not be called until all elements of `depends` array be truthy. Example: | ||
```javascript | ||
@@ -76,12 +95,28 @@ const {authToken} = useContext(authTokenContext); | ||
``` | ||
Motivation: you can apply hooks only at top level of function. | ||
Calling hooks inside `if` or `for` statements, or change count of hooks may throw React error. | ||
If any element of `depends` changed, request will be re-call. For example, you can use [react-use-trigger](https://github.com/ilyalesik/react-use-trigger) for re-call the request: | ||
```javascript | ||
// Potential сrash, because may call different count of hooks: | ||
const {authToken} = useContext(authTokenContext); | ||
if (!authToken) { | ||
return null; | ||
import {createTrigger, useTrigger} from "react-use-trigger"; | ||
const requestTrigger = createTrigger(); | ||
export const Subscriber = () => { | ||
const requestTriggerValue = useTrigger(requestTrigger); | ||
const { isLoading, data } = useFetch("https://swapi.co/api/people/1", { | ||
depends: [requestTriggerValue] | ||
}); | ||
return <div />; | ||
} | ||
const { isLoading, data } = useFetch("https://swapi.co/api/people/1"); | ||
export const Sender = () => { | ||
return <button onClick={() => { | ||
requestTrigger() // re-call request | ||
}}>Send</button> | ||
} | ||
``` | ||
@@ -129,2 +129,52 @@ import React from "react"; | ||
it("call with url, options with depends at next arg", async () => { | ||
fetch.mockResponse(JSON.stringify({ data: "12345" })); | ||
const options = { | ||
headers: { | ||
Accept: "application/json, application/xml, text/plain, text/html, *.*", | ||
"Content-Type": "application/json; charset=utf-8" | ||
} | ||
}; | ||
const fetchParams = ["https://google.com", options]; | ||
const Component = () => { | ||
const result = useFetch(...fetchParams, { depends: [true, false] }); | ||
return <div>{result.data && result.data.data}</div>; | ||
}; | ||
const { container, rerender } = render(<Component />); | ||
await wait(() => { | ||
rerender(<Component />); | ||
expect(fetch.mock.calls.length).toEqual(0); | ||
}); | ||
}); | ||
it("call with url, options with depends: [true] at next arg", async () => { | ||
fetch.mockResponse(JSON.stringify({ data: "12345" })); | ||
const options = { | ||
headers: { | ||
Accept: "application/json, application/xml, text/plain, text/html, *.*", | ||
"Content-Type": "application/json; charset=utf-8" | ||
} | ||
}; | ||
const fetchParams = ["https://google.com", options]; | ||
const Component = () => { | ||
const result = useFetch(...fetchParams, { depends: [true] }); | ||
return <div>{result.data && result.data.data}</div>; | ||
}; | ||
const { container, rerender } = render(<Component />); | ||
await wait(() => { | ||
rerender(<Component />); | ||
expect(fetch.mock.calls.length).toEqual(1); | ||
}); | ||
}); | ||
it("call with url, options with depends with empty string", async () => { | ||
@@ -131,0 +181,0 @@ fetch.mockResponse(JSON.stringify({ data: "12345" })); |
@@ -17,2 +17,5 @@ // @flow | ||
depends?: Array<boolean> | ||
}, | ||
specialOptions?: { | ||
depends?: Array<boolean> | ||
} | ||
@@ -26,6 +29,7 @@ ): TUseFetchResult<T> { | ||
}; | ||
const fetchInstance = formatter => (path, options) => { | ||
const fetchInstance = formatter => (path, options, specialOptions) => { | ||
const { depends, preventCallFetch, ...otherOptions } = options || {}; | ||
const _preventCallFetch = depends | ||
? depends.reduce((accumulator, currentValue) => accumulator || !currentValue, false) | ||
const _depends = (specialOptions && specialOptions.depends) || depends; | ||
const _preventCallFetch = _depends | ||
? _depends.reduce((accumulator, currentValue) => accumulator || !currentValue, false) | ||
: preventCallFetch; | ||
@@ -40,3 +44,3 @@ if (_preventCallFetch) { | ||
return usePromise((fetchInstance(formatter): any), path, fetchOptions); | ||
return usePromise((fetchInstance(formatter): any), path, fetchOptions, specialOptions); | ||
} else { | ||
@@ -43,0 +47,0 @@ return usePromise((fetchInstance(): any), path); |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
27800
17
510
119
31