@@ -200,6 +202,8 @@ const App = () => (
Suspense Mode (auto managed state)
+Can put `suspense` in 2 places. Either `useFetch` (A) or `Provider` (B).
+
```js
import useFetch, { Provider } from 'use-http'
@@ -207,7 +211,7 @@ function Todos() {
const { data: todos } = useFetch({
path: '/todos',
data: [],
- suspense: true // can put it in 2 places. Here or in Provider
+ suspense: true // A. can put `suspense: true` here
}, []) // onMount
return todos.map(todo =>
{todo.title}
)
@@ -215,7 +219,7 @@ function Todos() {
function App() {
const options = {
- suspense: true
+ suspense: true // B. can put `suspense: true` here too
}
return (
@@ -231,7 +235,7 @@ function App() {
-Suspense Mode (managed state)
+Suspense Mode (managed state)
Can put `suspense` in 2 places. Either `useFetch` (A) or `Provider` (B).
@@ -301,7 +305,7 @@ function App() {
-Pagination + Provider
+Pagination + Provider
The `onNewData` will take the current data, and the newly fetched data, and allow you to merge the two however you choose. In the example below, we are appending the new todos to the end of the current todos.
@@ -751,6 +755,46 @@ const App = () => {
+Retries retryOn & retryDelay
+
+In this example you can see how `retryOn` will retry on a status code of `305`, or if we choose the `retryOn()` function, it returns a boolean to decide if we will retry. With `retryDelay` we can either have a fixed delay, or a dynamic one by using `retryDelay()`. Make sure `retries` is set to at minimum `1` otherwise it won't retry the request. If `retries > 0` without `retryOn` then by default we always retry if there's an error or if `!response.ok`. If `retryOn: [400]` and `retries > 0` then we only retry on a response status of `400`.
+
+```js
+import useFetch from 'use-http'
+
+const TestRetry = () => {
+ const { response, get } = useFetch('https://httpbin.org/status/305', {
+ // make sure `retries` is set otherwise it won't retry
+ retries: 1,
+ retryOn: [305],
+ // OR
+ retryOn: ({ attempt, error, response }) => {
+ // returns true or false to determine whether to retry
+ return error || response && response.status >= 300
+ },
+
+ retryDelay: 3000,
+ // OR
+ retryDelay: ({ attempt, error, response }) => {
+ // exponential backoff
+ return Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)
+ // linear backoff
+ return attempt * 1000
+ }
+ })
+
+ return (
+ <>
+
+
{JSON.stringify(response, null, 2)}
+ >
+ )
+}
+```
+
+[](https://codesandbox.io/s/usefetch-retryon-retrydelay-s74q9)
+
+
Overview
--------
@@ -772,79 +816,108 @@ This is exactly what you would pass to the normal js `fetch`, with a little extr
| Option | Description | Default |
| --------------------- | --------------------------------------------------------------------------|------------- |
-| `suspense` | Enables Experimental React Suspense mode. [example](https://codesandbox.io/s/usefetch-suspense-i22wv) | false |
-| `cachePolicy` | These will be the same ones as Apollo's [fetch policies](https://www.apollographql.com/docs/react/api/react-apollo/#optionsfetchpolicy). Possible values are `cache-and-network`, `network-only`, `cache-only`, `no-cache`, `cache-first`. Currently only supports **`cache-first`** or **`no-cache`** | `cache-first` |
| `cacheLife` | After a successful cache update, that cache data will become stale after this duration | `0` |
-| `url` | Allows you to set a base path so relative paths can be used for each request :) | empty string |
-| `onNewData` | Merges the current data with the incoming data. Great for pagination. | `(curr, new) => new` |
-| `perPage` | Stops making more requests if there is no more data to fetch. (i.e. if we have 25 todos, and the perPage is 10, after fetching 2 times, we will have 20 todos. The last 5 tells us we don't have any more to fetch because it's less than 10) For pagination. | `0` |
-| `onAbort` | Runs when the request is aborted. | empty function |
-| `onTimeout` | Called when the request times out. | empty function |
-| `retries` | When a request fails or times out, retry the request this many times. By default it will not retry. | `0` |
-| `timeout` | The request will be aborted/cancelled after this amount of time. This is also the interval at which `retries` will be made at. **in milliseconds** | `30000` (30 seconds) |
+| `cachePolicy` | These will be the same ones as Apollo's [fetch policies](https://www.apollographql.com/docs/react/api/react-apollo/#optionsfetchpolicy). Possible values are `cache-and-network`, `network-only`, `cache-only`, `no-cache`, `cache-first`. Currently only supports **`cache-first`** or **`no-cache`** | `cache-first` |
| `data` | Allows you to set a default value for `data` | `undefined` |
-| `loading` | Allows you to set default value for `loading` | `false` unless the last argument of `useFetch` is `[]` |
| `interceptors.request` | Allows you to do something before an http request is sent out. Useful for authentication if you need to refresh tokens a lot. | `undefined` |
| `interceptors.response` | Allows you to do something after an http response is recieved. Useful for something like camelCasing the keys of the response. | `undefined` |
+| `loading` | Allows you to set default value for `loading` | `false` unless the last argument of `useFetch` is `[]` |
+| `onAbort` | Runs when the request is aborted. | empty function |
+| `onNewData` | Merges the current data with the incoming data. Great for pagination. | `(curr, new) => new` |
+| `onTimeout` | Called when the request times out. | empty function |
+| `path` | When using a global `url` set in the `Provider`, this is useful for adding onto it | `''` |
| `persist` | Persists data for the duration of `cacheLife`. If `cacheLife` is not set it defaults to 24h. Currently only available in Browser. | `false` |
+| `perPage` | Stops making more requests if there is no more data to fetch. (i.e. if we have 25 todos, and the perPage is 10, after fetching 2 times, we will have 20 todos. The last 5 tells us we don't have any more to fetch because it's less than 10) For pagination. | `0` |
+| `retries` | When a request fails or times out, retry the request this many times. By default it will not retry. | `0` |
+| `retryDelay` | You can retry with certain intervals i.e. 30 seconds `30000` or with custom logic (i.e. to increase retry intervals). | `1000` |
+| `retryOn` | You can retry on certain http status codes or have custom logic to decide whether to retry or not via a function. Make sure `retries > 0` otherwise it won't retry. | `[]` |
+| `suspense` | Enables Experimental React Suspense mode. [example](https://codesandbox.io/s/usefetch-suspense-i22wv) | `false` |
+| `timeout` | The request will be aborted/cancelled after this amount of time. This is also the interval at which `retries` will be made at. **in milliseconds**. If set to `0`, it will not timeout except for browser defaults. | `0` |
+| `url` | Allows you to set a base path so relative paths can be used for each request :) | empty string |
```jsx
const options = {
// accepts all `fetch` options such as headers, method, etc.
- // enables experimental React Suspense mode
- suspense: true, // defaults to `false`
+ // The time in milliseconds that cache data remains fresh.
+ cacheLife: 0,
// Cache responses to improve speed and reduce amount of requests
// Only one request to the same endpoint will be initiated unless cacheLife expires for 'cache-first'.
cachePolicy: 'cache-first' // 'no-cache'
+
+ // set's the default for the `data` field
+ data: [],
- // The time in milliseconds that cache data remains fresh.
- cacheLife: 0,
-
- // Allows caching to persist after page refresh. Only supported in the Browser currently.
- persist: false,
+ // typically, `interceptors` would be added as an option to the ``
+ interceptors: {
+ request: async (options, url, path, route) => { // `async` is not required
+ return options // returning the `options` is important
+ },
+ response: async (response) => {
+ // note: `response.data` is equivalent to `await response.json()`
+ return response // returning the `response` is important
+ }
+ },
- // used to be `baseUrl`. You can set your URL this way instead of as the 1st argument
- url: 'https://example.com',
-
- // called when the request times out
- onTimeout: () => {},
+ // set's the default for `loading` field
+ loading: false,
// called when aborting the request
onAbort: () => {},
- // this will allow you to merge the data however you choose. Used for Pagination
+ // this will allow you to merge the `data` for pagination.
onNewData: (currData, newData) => {
return [...currData, ...newData]
},
+ // called when the request times out
+ onTimeout: () => {},
+
+ // if you have a global `url` set up, this is how you can add to it
+ path: '/path/to/your/api',
+
// this will tell useFetch not to run the request if the list doesn't haveMore. (pagination)
// i.e. if the last page fetched was < 15, don't run the request again
perPage: 15,
+ // Allows caching to persist after page refresh. Only supported in the Browser currently.
+ persist: false,
+
// amount of times it should retry before erroring out
retries: 3,
+
+ // The time between retries
+ retryDelay: 10000,
+ // OR
+ // Can be a function which is used if we want change the time in between each retry
+ retryDelay({ attempt, error, response }) {
+ // exponential backoff
+ return Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)
+ // linear backoff
+ return attempt * 1000
+ },
+
+ // make sure `retries` is set otherwise it won't retry
+ // can retry on certain http status codes
+ retryOn: [503],
+ // OR
+ retryOn({ attempt, error, response }) {
+ // retry on any network error, or 4xx or 5xx status codes
+ if (error !== null || response.status >= 400) {
+ console.log(`retrying, attempt number ${attempt + 1}`);
+ return true;
+ }
+ },
+
+ // enables experimental React Suspense mode
+ suspense: true, // defaults to `false`
- // amount of time before the request (or request(s) for each retry) errors out.
+ // amount of time before the request get's canceled/aborted
timeout: 10000,
-
- // set's the default for the `data` field
- data: [],
-
- // set's the default for `loading` field
- loading: false,
-
- // typically, `interceptors` would be added as an option to the ``
- interceptors: {
- request: async (options, url, path, route) => { // `async` is not required
- return options // returning the `options` is important
- },
- response: async (response) => {
- // note: `response.data` is equivalent to `await response.json()`
- return response // returning the `response` is important
- }
- }
+
+ // used to be `baseUrl`. You can set your URL this way instead of as the 1st argument
+ url: 'https://example.com',
}
useFetch(options)
@@ -886,6 +959,11 @@ If you have feature requests, [submit an issue][1] to let us know what you would
Todos
------
+- [ ] dynamically check content-type to get data. [Common mime types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types)
+ - .arrayBuffer() []
+ - .json() ['application/json']
+ - .text() ['text/plain']
+ - .blob() ['image/png', 'application/octet-stream']
- [ ] suspense
- [ ] triggering it from outside the `` component.
- add `.read()` to `request`
@@ -909,35 +987,40 @@ Todos
- [ ] the `onMount` works properly with all variants of passing `useEffect(fn, [request.get])` and not causing an infinite loop
- [ ] `async` tests for `interceptors.response`
- [ ] aborts fetch on unmount
+ - [ ] does not abort fetch on every rerender
+ - [ ] `retryDelay` and `timeout` are both set. It works, but is annoying to deal with timers in tests. [resource](https://github.com/fac-13/HP-game/issues/9)
+ - [ ] `timeout` with `retries > 0`. (also do `retires > 1`) Need to figure out how to advance timers properly to write this and the test above
- [ ] take a look at how [react-apollo-hooks](https://github.com/trojanowski/react-apollo-hooks) work. Maybe ad `useSubscription` and `const request = useFetch(); request.subscribe()` or something along those lines
- [ ] make this a github package
- [see ava packages](https://github.com/orgs/ava/packages)
-- [ ] get it all working on a SSR codesandbox, this way we can have api to call locally
-- [ ] make GraphQL examples in codesandbox
- [ ] Documentation:
- [ ] show comparison with Apollo
- [ ] figure out a good way to show side-by-side comparisons
- [ ] show comparison with Axios
- - [ ] how this cancels a request on unmount of a component to avoid the error "cannot update state during a state transition" or something like that due to an incomplete http request
- [ ] maybe add syntax for middle helpers for inline `headers` or `queries` like this:
-```jsx
- const request = useFetch('https://example.com')
-
- request
- .headers({
- auth: jwt // this would inline add the `auth` header
- })
- .query({ // might have to use .params({ }) since we're using .query() for GraphQL
- no: 'way' // this would inline make the url: https://example.com?no=way
- })
- .get()
-```
+ ```jsx
+ const request = useFetch('https://example.com')
+
+ request
+ .headers({
+ auth: jwt // this would inline add the `auth` header
+ })
+ .query({ // might have to use .params({ }) since we're using .query() for GraphQL
+ no: 'way' // this would inline make the url: https://example.com?no=way
+ })
+ .get()
+ ```
- [ ] potential option ideas
```jsx
const request = useFetch({
+ graphql: {
+ // all options can also be put in here
+ // to overwrite those of `useFetch` for
+ // `useMutation` and `useQuery`
+ },
// Allows you to pass in your own cache to useFetch
// This is controversial though because `cache` is an option in the requestInit
// and it's value is a string. See: https://developer.mozilla.org/en-US/docs/Web/API/Request/cache
@@ -951,23 +1034,6 @@ Todos
request: async ({ options, url, path, route }) => {},
response: async ({ response }) => {}
},
- // can retry on certain http status codes
- retryOn: [503],
- // OR
- retryOn({ attempt, error, response }) {
- // retry on any network error, or 4xx or 5xx status codes
- if (error !== null || response.status >= 400) {
- console.log(`retrying, attempt number ${attempt + 1}`);
- return true;
- }
- },
- // This function receives a retryAttempt integer and returns the delay to apply before the next attempt in milliseconds
- retryDelay({ attempt, error, response }) {
- // applies exponential backoff
- return Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)
- // applies linear backoff
- return attempt * 1000
- },
// these will be the exact same ones as Apollo's
cachePolicy: 'cache-and-network', 'network-only', 'cache-only', 'no-cache' // 'cache-first'
// potential idea to fetch on server instead of just having `loading` state. Not sure if this is a good idea though
@@ -983,64 +1049,28 @@ Todos
})
```
-- resources
- - [retryOn/retryDelay (fetch-retry)](https://www.npmjs.com/package/fetch-retry#example-retry-on-503-service-unavailable)
- - [retryDelay (react-query)](https://github.com/tannerlinsley/react-query)
-
- [ ] potential option ideas for `GraphQL`
-```jsx
-const request = useQuery({ onMount: true })`your graphql query`
-
-const request = useFetch(...)
-const userID = 'some-user-uuid'
-const res = await request.query({ userID })`
- query Todos($userID string!) {
- todos(userID: $userID) {
- id
- title
- }
- }
-`
-```
-
-- [ ] make code editor plugin/package/extension that adds GraphQL syntax highlighting for `useQuery` and `useMutation` 😊
+ ```jsx
+ const request = useQuery({ onMount: true })`your graphql query`
-GraphQL with Suspense (not implemented yet)
-
-```jsx
-const App = () => {
- const [todoTitle, setTodoTitle] = useState('')
- // if there's no used, useMutation works this way
- const mutation = useMutation('http://example.com', `
- mutation CreateTodo($todoTitle string) {
- todo(title: $todoTitle) {
+ const request = useFetch(...)
+ const userID = 'some-user-uuid'
+ const res = await request.query({ userID })`
+ query Todos($userID string!) {
+ todos(userID: $userID) {
id
title
}
}
- `)
-
- // ideally, I think it should be mutation.write({ todoTitle }) since mutation ~= POST
- const createTodo = () => mutation.read({ todoTitle })
-
- if (!request.data) return null
-
- return (
- <>
- setTodoTitle(e.target.value)} />
-
-
{mutation.data}
- >
- )
-}
-```
-
+ `
+ ```
+- [ ] make code editor plugin/package/extension that adds GraphQL syntax highlighting for `useQuery` and `useMutation` 😊
[1]: https://github.com/alex-cory/use-http/issues/new?title=[Feature%20Request]%20YOUR_FEATURE_NAME
[2]: https://github.com/alex-cory/use-http/issues/93#issuecomment-600896722
[3]: https://github.com/alex-cory/use-http/raw/master/public/dog.png
[4]: https://reactjs.org/docs/javascript-environment-requirements.html
[5]: http://use-http.com
-[`react-app-polyfill`]: https://www.npmjs.com/package/react-app-polyfill
\ No newline at end of file
+[`react-app-polyfill`]: https://www.npmjs.com/package/react-app-polyfill
diff --git a/config/setupTests.ts b/config/setupTests.ts
index 7187804c..870f39eb 100644
--- a/config/setupTests.ts
+++ b/config/setupTests.ts
@@ -3,19 +3,3 @@ import { GlobalWithFetchMock } from 'jest-fetch-mock'
const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock
customGlobal.fetch = require('jest-fetch-mock')
customGlobal.fetchMock = customGlobal.fetch
-
-// this is just a little hack to silence a warning that we'll get until react
-// fixes this: https://github.com/facebook/react/pull/14853
-const originalError = console.error
-beforeAll(() => {
- console.error = (...args: any[]) => {
- if (/Warning.*not wrapped in act/.test(args[0])) {
- return
- }
- originalError.call(console, ...args)
- }
-})
-
-afterAll(() => {
- console.error = originalError
-})
diff --git a/docs/README.md b/docs/README.md
index dab62717..2941d0a5 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -61,6 +61,7 @@ Features
- Built in caching
- Persistent caching support
- Suspense(experimental) support
+- Retry functionality
Examples
=========
@@ -68,9 +69,10 @@ Examples
- useFetch + Next.js
- useFetch + create-react-app
- useFetch + Provider
--
+- useFetch + Suspense
- useFetch + Pagination + Provider
- useFetch + Request/Response Interceptors + Provider
+- useFetch + retryOn, retryDelay
- useQuery - GraphQL
Installation
@@ -574,6 +576,46 @@ const App = () => {
}
```
+Retries
+-------
+
+In this example you can see how `retryOn` will retry on a status code of `305`, or if we choose the `retryOn()` function, it returns a boolean to decide if we will retry. With `retryDelay` we can either have a fixed delay, or a dynamic one by using `retryDelay()`. Make sure `retries` is set to at minimum `1` otherwise it won't retry the request. If `retries > 0` without `retryOn` then by default we always retry if there's an error or if `!response.ok`. If `retryOn: [400]` and `retries > 0` then we only retry on a response status of `400`, not on any generic network error.
+
+```js
+import useFetch from 'use-http'
+
+const TestRetry = () => {
+ const { response, get } = useFetch('https://httpbin.org/status/305', {
+ // make sure `retries` is set otherwise it won't retry
+ retries: 1,
+ retryOn: [305],
+ // OR
+ retryOn: ({ attempt, error, response }) => {
+ // returns true or false to determine whether to retry
+ return error || response && response.status >= 300
+ },
+
+ retryDelay: 3000,
+ // OR
+ retryDelay: ({ attempt, error, response }) => {
+ // exponential backoff
+ return Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)
+ // linear backoff
+ return attempt * 1000
+ }
+ })
+
+ return (
+ <>
+
+
{JSON.stringify(response, null, 2)}
+ >
+ )
+}
+```
+
+[](https://codesandbox.io/s/usefetch-retryon-retrydelay-s74q9)
+
GraphQL Query
---------------
@@ -720,8 +762,8 @@ function App() {
Hooks
=======
-| Option | Description |
-| --------------------- | ---------------------------------------------------------------------------------------- |
+| Option | Description |
+| --------------------- | ------------------ |
| `useFetch` | The base hook |
| `useQuery` | For making a GraphQL query |
| `useMutation` | For making a GraphQL mutation |
@@ -733,79 +775,109 @@ This is exactly what you would pass to the normal js `fetch`, with a little extr
| Option | Description | Default |
| --------------------- | --------------------------------------------------------------------------|------------- |
-| `suspense` | Enables React Suspense mode. [example](https://codesandbox.io/s/usefetch-suspense-i22wv) | false |
-| `cachePolicy` | These will be the same ones as Apollo's [fetch policies](https://www.apollographql.com/docs/react/api/react-apollo/#optionsfetchpolicy). Possible values are `cache-and-network`, `network-only`, `cache-only`, `no-cache`, `cache-first`. Currently only supports **`cache-first`** or **`no-cache`** | `cache-first` |
| `cacheLife` | After a successful cache update, that cache data will become stale after this duration | `0` |
-| `url` | Allows you to set a base path so relative paths can be used for each request :) | empty string |
-| `onNewData` | Merges the current data with the incoming data. Great for pagination. | `(curr, new) => new` |
-| `perPage` | Stops making more requests if there is no more data to fetch. (i.e. if we have 25 todos, and the perPage is 10, after fetching 2 times, we will have 20 todos. The last 5 tells us we don't have any more to fetch because it's less than 10) For pagination. | `0` |
-| `onAbort` | Runs when the request is aborted. | empty function |
-| `onTimeout` | Called when the request times out. | empty function |
-| `retries` | When a request fails or times out, retry the request this many times. By default it will not retry. | `0` |
-| `timeout` | The request will be aborted/cancelled after this amount of time. This is also the interval at which `retries` will be made at. **in milliseconds** | `30000` (30 seconds) |
+| `cachePolicy` | These will be the same ones as Apollo's [fetch policies](https://www.apollographql.com/docs/react/api/react-apollo/#optionsfetchpolicy). Possible values are `cache-and-network`, `network-only`, `cache-only`, `no-cache`, `cache-first`. Currently only supports **`cache-first`** or **`no-cache`** | `cache-first` |
| `data` | Allows you to set a default value for `data` | `undefined` |
-| `loading` | Allows you to set default value for `loading` | `false` unless the last argument of `useFetch` is `[]` |
| `interceptors.request` | Allows you to do something before an http request is sent out. Useful for authentication if you need to refresh tokens a lot. | `undefined` |
| `interceptors.response` | Allows you to do something after an http response is recieved. Useful for something like camelCasing the keys of the response. | `undefined` |
+| `loading` | Allows you to set default value for `loading` | `false` unless the last argument of `useFetch` is `[]` |
+| `onAbort` | Runs when the request is aborted. | empty function |
+| `onNewData` | Merges the current data with the incoming data. Great for pagination. | `(curr, new) => new` |
+| `onTimeout` | Called when the request times out. | empty function |
+| `path` | When using a global `url` set in the `Provider`, this is useful for adding onto it | `''` |
| `persist` | Persists data for the duration of `cacheLife`. If `cacheLife` is not set it defaults to 24h. Currently only available in Browser. | `false` |
+| `perPage` | Stops making more requests if there is no more data to fetch. (i.e. if we have 25 todos, and the perPage is 10, after fetching 2 times, we will have 20 todos. The last 5 tells us we don't have any more to fetch because it's less than 10) For pagination. | `0` |
+| `retries` | When a request fails or times out, retry the request this many times. By default it will not retry. | `0` |
+| `retryDelay` | You can retry with certain intervals i.e. 30 seconds `30000` or with custom logic (i.e. to increase retry intervals). | `1000` |
+| `retryOn` | You can retry on certain http status codes or have custom logic to decide whether to retry or not via a function. Make sure `retries > 0` otherwise it won't retry. | `[]` |
+| `suspense` | Enables Experimental React Suspense mode. [example](https://codesandbox.io/s/usefetch-suspense-i22wv) | `false` |
+| `timeout` | The request will be aborted/cancelled after this amount of time. This is also the interval at which `retries` will be made at. **in milliseconds**. If set to `0`, it will not timeout except for browser defaults. | `0` |
+| `url` | Allows you to set a base path so relative paths can be used for each request :) | empty string |
```jsx
const options = {
// accepts all `fetch` options such as headers, method, etc.
-
- // enables React Suspense mode
- suspense: true, // defaults to `false`
+
+ // The time in milliseconds that cache data remains fresh.
+ cacheLife: 0,
// Cache responses to improve speed and reduce amount of requests
// Only one request to the same endpoint will be initiated unless cacheLife expires for 'cache-first'.
cachePolicy: 'cache-first' // 'no-cache'
+
+ // set's the default for the `data` field
+ data: [],
- // The time in milliseconds that cache data remains fresh.
- cacheLife: 0,
-
- // Allows caching to persist after page refresh. Only supported in the Browser currently.
- persist: false,
+ // typically, `interceptors` would be added as an option to the ``
+ interceptors: {
+ request: async (options, url, path, route) => { // `async` is not required
+ return options // returning the `options` is important
+ },
+ response: async (response) => {
+ // note: `response.data` is equivalent to `await response.json()`
+ return response // returning the `response` is important
+ }
+ },
- // used to be `baseUrl`. You can set your URL this way instead of as the 1st argument
- url: 'https://example.com',
-
- // called when the request times out
- onTimeout: () => {},
+ // set's the default for `loading` field
+ loading: false,
// called when aborting the request
onAbort: () => {},
- // this will allow you to merge the data however you choose. Used for Pagination
+ // this will allow you to merge the `data` for pagination.
onNewData: (currData, newData) => {
return [...currData, ...newData]
},
+ // called when the request times out
+ onTimeout: () => {},
+
+ // if you have a global `url` set up, this is how you can add to it
+ path: '/path/to/your/api',
+
// this will tell useFetch not to run the request if the list doesn't haveMore. (pagination)
// i.e. if the last page fetched was < 15, don't run the request again
perPage: 15,
+ // Allows caching to persist after page refresh. Only supported in the Browser currently.
+ persist: false,
+
// amount of times it should retry before erroring out
retries: 3,
+
+ // The time between retries
+ retryDelay: 10000,
+ // OR
+ // Can be a function which is used if we want change the time in between each retry
+ retryDelay({ attempt, error, response }) {
+ // exponential backoff
+ return Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000)
+ // linear backoff
+ return attempt * 1000
+ },
+
+
+ // make sure `retries` is set otherwise it won't retry
+ // can retry on certain http status codes
+ retryOn: [503],
+ // OR
+ retryOn({ attempt, error, response }) {
+ // retry on any network error, or 4xx or 5xx status codes
+ if (error !== null || response.status >= 400) {
+ console.log(`retrying, attempt number ${attempt + 1}`);
+ return true;
+ }
+ },
+
+ // enables experimental React Suspense mode
+ suspense: true, // defaults to `false`
- // amount of time before the request (or request(s) for each retry) errors out.
+ // amount of time before the request get's canceled/aborted
timeout: 10000,
-
- // set's the default for the `data` field
- data: [],
-
- // set's the default for `loading` field
- loading: false,
-
- // typically, `interceptors` would be added as an option to the ``
- interceptors: {
- request: async (options, url, path, route) => { // `async` is not required
- return options // returning the `options` is important
- },
- response: async (response) => { // `async` is not required
- // note: `response.data` is equivalent to `await response.json()`
- return response // returning the `response` is important
- }
- }
+
+ // used to be `baseUrl`. You can set your URL this way instead of as the 1st argument
+ url: 'https://example.com',
}
useFetch(options)
@@ -883,4 +955,4 @@ const App = () => {
[2]: https://github.com/alex-cory/use-http/issues/93#issuecomment-600896722
[3]: https://github.com/alex-cory/use-http/raw/master/public/dog.png
[4]: https://reactjs.org/docs/javascript-environment-requirements.html
-[`react-app-polyfill`]: https://www.npmjs.com/package/react-app-polyfill
\ No newline at end of file
+[`react-app-polyfill`]: https://www.npmjs.com/package/react-app-polyfill
diff --git a/package.json b/package.json
index e627a29c..f6045688 100644
--- a/package.json
+++ b/package.json
@@ -12,41 +12,42 @@
"use-ssr": "^1.0.22"
},
"peerDependencies": {
- "react": "^16.13.0",
- "react-dom": "^16.13.0"
+ "react": "^16.13.1",
+ "react-dom": "^16.13.1"
},
"devDependencies": {
- "@testing-library/react": "^10.0.0",
- "@testing-library/react-hooks": "^3.0.0",
- "@types/fetch-mock": "^7.2.3",
- "@types/jest": "^25.1.0",
- "@types/node": "^13.9.0",
- "@types/react": "^16.9.23",
- "@types/react-dom": "^16.8.4",
- "@typescript-eslint/eslint-plugin": "^2.23.0",
- "@typescript-eslint/parser": "^2.23.0",
+ "@testing-library/react": "^10.0.2",
+ "@testing-library/react-hooks": "^3.2.1",
+ "@types/fetch-mock": "^7.3.2",
+ "@types/jest": "^25.1.4",
+ "@types/node": "^13.9.8",
+ "@types/react": "^16.9.30",
+ "@types/react-dom": "^16.9.5",
+ "@typescript-eslint/eslint-plugin": "^2.26.0",
+ "@typescript-eslint/parser": "^2.26.0",
"convert-keys": "^1.3.4",
"eslint": "^6.8.0",
- "eslint-config-standard": "^14.1.0",
- "eslint-plugin-import": "^2.20.1",
- "eslint-plugin-jest": "23.8.2",
+ "eslint-config-standard": "^14.1.1",
+ "eslint-plugin-import": "^2.20.2",
+ "eslint-plugin-jest": "^23.8.2",
"eslint-plugin-jest-formatting": "^1.2.0",
- "eslint-plugin-jsx-a11y": "^6.2.1",
- "eslint-plugin-node": "^11.0.0",
+ "eslint-plugin-jsx-a11y": "^6.2.3",
+ "eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.19.0",
- "eslint-plugin-react-hooks": "^2.5.0",
+ "eslint-plugin-react-hooks": "^3.0.0",
"eslint-plugin-standard": "^4.0.1",
"eslint-watch": "^6.0.1",
- "jest": "^25.1.0",
+ "jest": "^25.2.4",
"jest-fetch-mock": "^3.0.3",
+ "jest-mock-console": "^1.0.0",
"mockdate": "^2.0.5",
- "react": "^16.8.6",
- "react-dom": "^16.8.6",
+ "react": "^16.13.1",
+ "react-dom": "^16.13.1",
"react-hooks-testing-library": "^0.6.0",
- "react-test-renderer": "^16.8.6",
- "ts-jest": "^25.2.1",
- "typescript": "^3.4.5",
+ "react-test-renderer": "^16.13.1",
+ "ts-jest": "^25.3.0",
+ "typescript": "^3.8.3",
"utility-types": "^3.10.0",
"watch": "^1.0.2"
},
diff --git a/src/__tests__/useFetch.test.tsx b/src/__tests__/useFetch.test.tsx
index 1572bed1..af2b2d76 100644
--- a/src/__tests__/useFetch.test.tsx
+++ b/src/__tests__/useFetch.test.tsx
@@ -1,54 +1,22 @@
/* eslint-disable no-var */
/* eslint-disable camelcase */
/* eslint-disable @typescript-eslint/camelcase */
-import React, { Suspense, ReactElement, ReactNode } from 'react'
+import React, { ReactElement, ReactNode } from 'react'
import { useFetch, Provider } from '..'
import { cleanup } from '@testing-library/react'
import { FetchMock } from 'jest-fetch-mock'
-import { Res, Options, CachePolicies } from '../types'
import { toCamel } from 'convert-keys'
import { renderHook, act } from '@testing-library/react-hooks'
-import { emptyCustomResponse } from '../utils'
-import * as test from '@testing-library/react'
-import ErrorBoundary from '../ErrorBoundary'
-
+import mockConsole from 'jest-mock-console'
import * as mockdate from 'mockdate'
+import { Res, Options, CachePolicies } from '../types'
+import { emptyCustomResponse, sleep, makeError } from '../utils'
+
const fetch = global.fetch as FetchMock
const { NO_CACHE, NETWORK_ONLY } = CachePolicies
-// Provider Tests =================================================
-/**
- * Test Cases
- * Provider:
- * 1. URL only
- * 2. Options only
- * 3. graphql only
- * 4. URL and Options only
- * 5. URL and graphql only
- * 6. Options and graphql only
- * 7. URL and graphql and Options
- * useFetch:
- * A. const [data, loading, error, request] = useFetch()
- * B. const {data, loading, error, request} = useFetch()
- * C. const [data, loading, error, request] = useFetch('http://url.com')
- * D. const [data, loading, error, request] = useFetch('http://url.com', { onMount: true })
- * E. const [data, loading, error, request] = useFetch({ onMount: true })
- * F. const [data, loading, error, request] = useFetch({ url: 'http://url.com' })
- * G. const [data, loading, error, request] = useFetch(oldOptions => ({ ...newOptions }))
- * H. const [data, loading, error, request] = useFetch('http://url.com', oldOptions => ({ ...newOptions }))
- * Errors:
- * SSR Tests:
- */
-
-/**
- * Tests to add:
- * - FormData
- * - React Native
- * - more `interceptor` tests. Specifically for the `data` that is not in the `response` object
- */
-
describe('useFetch - BROWSER - basic functionality', (): void => {
const expected = {
name: 'Alex Cory',
@@ -66,9 +34,7 @@ describe('useFetch - BROWSER - basic functionality', (): void => {
fetch.mockResponseOnce(JSON.stringify(expected))
})
- it('should execute GET command with object destructuring', async (): Promise<
- void
- > => {
+ it('should execute GET command with object destructuring', async (): Promise => {
const { result, waitForNextUpdate } = renderHook(
() => useFetch('https://example.com', []), // onMount === true
{ wrapper: wrapper as React.ComponentType }
@@ -100,9 +66,7 @@ describe('useFetch - BROWSER - basic functionality', (): void => {
expect(typeof result.current.mutate).toBe('function')
})
- it('should execute GET command with arrray destructuring', async (): Promise<
- void
- > => {
+ it('should execute GET command with arrray destructuring', async (): Promise => {
const { result, waitForNextUpdate } = renderHook(
() => useFetch('sweet', []), // onMount === true
{ wrapper: wrapper as React.ComponentType }
@@ -118,6 +82,21 @@ describe('useFetch - BROWSER - basic functionality', (): void => {
expect(request.loading).toBe(false)
expect(loading).toBe(false)
})
+
+ it('should not be content-type: application/json by default if using FormData for request body', async (): Promise => {
+ const { result } = renderHook(
+ () => useFetch('url-1234567'),
+ { wrapper: wrapper as React.ComponentType }
+ )
+ await act(async () => {
+ var formData = new FormData()
+ formData.append('username', 'AlexCory')
+ await result.current.post(formData)
+ const options = fetch.mock.calls[0][1] || {}
+ expect(options.method).toBe('POST')
+ expect(options.headers).toBeUndefined()
+ })
+ })
})
describe('useFetch - BROWSER - with ', (): void => {
@@ -139,9 +118,7 @@ describe('useFetch - BROWSER - with ', (): void => {
fetch.mockResponseOnce(JSON.stringify(expected))
})
- it('should work correctly: useFetch({ onMount: true, data: [] })', async (): Promise<
- void
- > => {
+ it('should work correctly: useFetch({ onMount: true, data: [] })', async (): Promise => {
const { result, waitForNextUpdate } = renderHook(
() => useFetch({ data: {} }, []), // onMount === true
{ wrapper }
@@ -154,9 +131,7 @@ describe('useFetch - BROWSER - with ', (): void => {
expect(result.current.data).toMatchObject(expected)
})
- it('should execute GET using Provider url', async (): Promise<
- void
- > => {
+ it('should execute GET using Provider url', async (): Promise => {
const { result, waitForNextUpdate } = renderHook(
() => useFetch({ data: {} }, []), // onMount === true
{ wrapper }
@@ -168,29 +143,25 @@ describe('useFetch - BROWSER - with ', (): void => {
expect(result.current.data).toMatchObject(expected)
})
- it('should execute GET using Provider url: request = useFetch(), request.get()', async (): Promise<
- void
- > => {
+ it('should execute GET using Provider url: request = useFetch(), request.get()', async (): Promise => {
const { result } = renderHook(() => useFetch(), { wrapper })
expect(result.current.loading).toBe(false)
- await result.current.get()
+ await act(result.current.get)
expect(result.current.loading).toBe(false)
expect(result.current.data).toMatchObject(expected)
})
- it('should execute GET using Provider url: request = useFetch(), request.get("/people")', async (): Promise<
- void
- > => {
+ it('should execute GET using Provider url: request = useFetch(), request.get("/people")', async (): Promise => {
const { result } = renderHook(() => useFetch(), { wrapper })
expect(result.current.loading).toBe(false)
- await result.current.get('/people')
+ await act(async () => {
+ await result.current.get('/people')
+ })
expect(result.current.loading).toBe(false)
expect(result.current.data).toMatchObject(expected)
})
- it('should merge the data onNewData for pagination', async (): Promise<
- void
- > => {
+ it('should merge the data onNewData for pagination', async (): Promise => {
const { result, waitForNextUpdate } = renderHook(
() => useFetch({
path: '/people',
@@ -208,17 +179,12 @@ describe('useFetch - BROWSER - with ', (): void => {
})
})
- it('should not make another request when there is no more data `perPage` pagination', async (): Promise<
- void
- > => {
+ it('should not make another request when there is no more data `perPage` pagination', async (): Promise => {
fetch.resetMocks()
const expected1 = [1, 2, 3]
- fetch.mockResponse(
- JSON.stringify(expected1)
- )
- let page = 1
+ fetch.mockResponse(JSON.stringify(expected1))
const { result, rerender, waitForNextUpdate } = renderHook(
- () => useFetch(`https://example.com?page=${page}`, {
+ ({ page }) => useFetch(`https://example.com?page=${page}`, {
data: [],
perPage: 3,
onNewData: (currData, newData) => {
@@ -226,19 +192,22 @@ describe('useFetch - BROWSER - with ', (): void => {
if (page === 2) return [...currData, 4]
return [...currData, ...newData]
}
- }, [page]) // onMount === true
+ }, [page]), // onMount === true
+ {
+ initialProps: { page: 1 },
+ wrapper
+ }
)
expect(result.current.loading).toBe(true)
await waitForNextUpdate()
expect(result.current.loading).toBe(false)
expect(result.current.data).toEqual(expected1)
- page = 2
- rerender()
+ act(() => rerender({ page: 2 }))
await waitForNextUpdate()
expect(result.current.data).toEqual([...expected1, 4])
expect(fetch.mock.calls.length).toBe(2)
- page = 3
- rerender()
+ act(() => rerender({ page: 3 }))
+ await waitForNextUpdate()
expect(result.current.data).toEqual([...expected1, 4])
expect(fetch.mock.calls.length).toBe(2)
})
@@ -280,9 +249,7 @@ describe('timeouts', (): void => {
jest.useFakeTimers()
})
- it(`should execute GET and timeout after ${timeout}ms, and fire 'onTimeout' and 'onAbort'`, async (): Promise<
- void
- > => {
+ it(`should execute GET and timeout after ${timeout}ms, and fire 'onTimeout' and 'onAbort'`, async (): Promise => {
const onAbort = jest.fn()
const onTimeout = jest.fn()
const { result, waitForNextUpdate } = renderHook(
@@ -309,14 +276,15 @@ describe('timeouts', (): void => {
expect(onTimeout).toHaveBeenCalledTimes(1)
})
- it(`should execute GET, fail after ${timeout}ms, then retry 1 additional time`, async (): Promise<
- void
- > => {
+ it(`should execute GET, fail after ${timeout}ms, then retry 1 additional time`, async (): Promise => {
const onAbort = jest.fn()
const onTimeout = jest.fn()
const { result, waitForNextUpdate } = renderHook(
() => useFetch({
retries: 1,
+ // TODO: this test times out if `retryDelay > 0`
+ // works in apps, not sure how to advance the timers correctly
+ retryDelay: 0,
timeout,
path: '/todos',
onAbort,
@@ -363,9 +331,11 @@ describe('caching - useFetch - BROWSER', (): void => {
await waitForNextUpdate()
expect(result.current.loading).toBe(false)
expect(result.current.data).toEqual(expected)
- // make a 2nd request
- const responseData = await result.current.get()
- expect(responseData).toEqual(expected)
+ await act(async () => {
+ // make a 2nd request
+ const responseData = await result.current.get()
+ expect(responseData).toEqual(expected)
+ })
expect(result.current.data).toEqual(expected)
expect(fetch.mock.calls.length).toBe(1)
expect(result.current.loading).toBe(false)
@@ -378,14 +348,12 @@ describe('caching - useFetch - BROWSER', (): void => {
await waitForNextUpdate()
const { response } = result.current
expect(result.current.loading).toBe(false)
- let text
- let json
await act(async () => {
- json = await result.current.get()
- text = await response.text()
+ const json = await result.current.get()
+ const text = await response.text()
+ expect(text).toBe(JSON.stringify(expected))
+ expect(json).toEqual(expected)
})
- expect(text).toBe(JSON.stringify(expected))
- expect(json).toEqual(expected)
})
it('should still have a `response` promise even when being cached. `cache-first` cachePolicy (array destructuring)', async (): Promise => {
@@ -395,14 +363,12 @@ describe('caching - useFetch - BROWSER', (): void => {
await waitForNextUpdate()
var [, response] = result.current
expect(result.current.loading).toBe(false)
- let text
- let json
await act(async () => {
- json = await result.current.get()
- text = await response.text()
+ const json = await result.current.get()
+ const text = await response.text()
+ expect(text).toBe(JSON.stringify(expected))
+ expect(json).toEqual(expected)
})
- expect(text).toBe(JSON.stringify(expected))
- expect(json).toEqual(expected)
})
it('should make a second request if cacheLife has exprired. `cache-first` cachePolicy', async (): Promise => {
@@ -415,10 +381,10 @@ describe('caching - useFetch - BROWSER', (): void => {
expect(result.current.loading).toBe(false)
expect(result.current.data).toEqual(expected)
expect(fetch.mock.calls.length).toEqual(1)
- // wait ~20ms to allow cache to expire
- await new Promise(resolve => setTimeout(resolve, 20))
- // make a 2nd request
await act(async () => {
+ // wait ~20ms to allow cache to expire
+ await sleep(20)
+ // make a 2nd request
await result.current.get()
})
expect(result.current.data).toEqual(expected)
@@ -451,8 +417,10 @@ describe('useFetch - BROWSER - with - Managed State', (): void => {
{ wrapper: wrapper as React.ComponentType }
)
expect(result.current.loading).toBe(false)
- const responseData = await result.current.post('/people', expected)
- expect(responseData).toEqual(expected)
+ await act(async () => {
+ const responseData = await result.current.post('/people', expected)
+ expect(responseData).toEqual(expected)
+ })
expect(result.current.data).toEqual(expected)
expect(result.current.loading).toBe(false)
})
@@ -550,9 +518,7 @@ describe('useFetch - BROWSER - interceptors', (): void => {
})
beforeEach((): void => {
- fetch.mockResponseOnce(
- JSON.stringify(snake_case)
- )
+ fetch.mockResponseOnce(JSON.stringify(snake_case))
})
it('should pass the proper response object for `interceptors.response`', async (): Promise => {
@@ -560,19 +526,17 @@ describe('useFetch - BROWSER - interceptors', (): void => {
() => useFetch(),
{ wrapper }
)
- await result.current.get()
+ await act(result.current.get)
expect(result.current.response.ok).toBe(true)
expect(result.current.response.data).toEqual(expected)
})
it('should have the `data` field correctly set when using a response interceptor', async (): Promise => {
const { result } = renderHook(
- () => useFetch('x'),
+ () => useFetch(),
{ wrapper }
)
- await act(async () => {
- await result.current.get()
- })
+ await act(result.current.get)
expect(result.current.response.ok).toBe(true)
expect(result.current.data).toEqual(expected)
})
@@ -582,7 +546,7 @@ describe('useFetch - BROWSER - interceptors', (): void => {
() => useFetch({ path: '/path' }),
{ wrapper }
)
- await result.current.get()
+ await act(result.current.get)
expect((fetch.mock.calls[0][1] as any).data).toEqual('path')
})
@@ -591,7 +555,9 @@ describe('useFetch - BROWSER - interceptors', (): void => {
() => useFetch(),
{ wrapper }
)
- await result.current.get('/route')
+ await act(async () => {
+ await result.current.get('/route')
+ })
expect((fetch.mock.calls[0][1] as any).data).toEqual('route')
})
@@ -600,7 +566,7 @@ describe('useFetch - BROWSER - interceptors', (): void => {
() => useFetch('url'),
{ wrapper }
)
- await result.current.get()
+ await act(result.current.get)
expect((fetch.mock.calls[0][1] as any).data).toEqual('url')
})
})
@@ -634,14 +600,16 @@ describe('useFetch - BROWSER - Overwrite Global Options set in Provider', (): vo
() => useFetch(),
{ wrapper }
)
- await result.current.get()
- expect(fetch.mock.calls[0][0]).toBe('https://example.com')
- expect((fetch.mock.calls[0][1] as any).headers).toEqual(expectedHeadersGET)
- await result.current.post()
- expect((fetch.mock.calls[1][1] as any).headers).toEqual(expectedHeadersPOSTandPUT)
- await result.current.put()
- expect((fetch.mock.calls[2][1] as any).headers).toEqual(expectedHeadersPOSTandPUT)
- expect(fetch).toHaveBeenCalledTimes(3)
+ await act(async () => {
+ await result.current.get()
+ expect(fetch.mock.calls[0][0]).toBe('https://example.com')
+ expect((fetch.mock.calls[0][1] as any).headers).toEqual(expectedHeadersGET)
+ await result.current.post()
+ expect((fetch.mock.calls[1][1] as any).headers).toEqual(expectedHeadersPOSTandPUT)
+ await result.current.put()
+ expect((fetch.mock.calls[2][1] as any).headers).toEqual(expectedHeadersPOSTandPUT)
+ expect(fetch).toHaveBeenCalledTimes(3)
+ })
})
it('should have the correct headers set in the options set in the Provider', async (): Promise => {
@@ -650,7 +618,7 @@ describe('useFetch - BROWSER - Overwrite Global Options set in Provider', (): vo
() => useFetch(),
{ wrapper }
)
- await result.current.get()
+ await act(result.current.get)
expect(fetch.mock.calls[0][0]).toBe('https://example.com')
expect((fetch.mock.calls[0][1] as any).headers).toEqual(expectedHeaders)
expect(fetch).toHaveBeenCalledTimes(1)
@@ -698,72 +666,238 @@ describe('useFetch - BROWSER - suspense', (): void => {
afterEach((): void => {
fetch.resetMocks()
cleanup()
-
- test.cleanup()
})
+ const expected = 'yay suspense'
beforeEach((): void => {
- fetch.mockResponse(JSON.stringify('yay suspense'))
+ fetch.mockResponse(JSON.stringify(expected))
})
it('should render useFetch fallback', async () => {
- function Section() {
- const { data } = useFetch('https://a.co', { suspense: true }, [])
- return