Skip to content

Commit 2a45ae2

Browse files
committed
improvement: deferFn and promiseFn now have the same signature.
The `promiseFn` and the `deferFn` have been unified. They now share the following signature: ```ts export type AsyncFn<T, C> = ( context: C | undefined, props: AsyncProps<T, C>, controller: AbortController ) => Promise<T> ``` Before the `deferFn` and `promiseFn` had this signature: ```ts export type PromiseFn<T> = (props: AsyncProps<T>, controller: AbortController) => Promise<T> export type DeferFn<T> = ( args: any[], props: AsyncProps<T>, controller: AbortController ) => Promise<T> ``` The big change is the introduction of the `context` parameter. The idea behind this parameter is that it will contain the parameters which are not known to `AsyncOptions` for use in the `promiseFn` and `asyncFn`. Another goal of this commit is to make TypeScript more understanding of the `context` which `AsyncProps` implicitly carries around. Before this commit the `AsyncProps` accepted extra prop via `[prop: string]: any`. This breaks TypeScript's understanding of the divisions somewhat. This also led to missing types for `onCancel` and `suspense`, which have been added in this commit. To solve this we no longer allow random extra properties that are unknown to `AsyncProps`. Instead only the new `context` of `AsyncProps` is passed. This means that the `[prop: string]: any` of `AsyncProps` is removed this makes TypeScript understand the props better. The other big change of this commit that `useAsync` no longer supports an overload. This means that the user can no longer do: ```ts const state = useAsync(loadPlayer, { context: { playerId: 1 } }) ``` But have to be more explicit: ```t const state = useAsync({ promiseFn: loadPlayer, context: { playerId: 1 } }) ``` These changes are of course a breaking change. Also now compiling TypeScript on `yarn test` this should prevent type errors from slipping in. Closes: #246 WIP: Trying to fix build asdf
1 parent 2664df0 commit 2a45ae2

File tree

32 files changed

+405
-180
lines changed

32 files changed

+405
-180
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,5 @@ lerna-debug.log*
1515
# when working with contributors
1616
package-lock.json
1717
yarn.lock
18+
19+
.vscode

.travis.yml

+3
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,6 @@ cache:
88
script: yarn && yarn ci
99
after_success:
1010
- bash <(curl -s https://codecov.io/bash) -e TRAVIS_NODE_VERSION
11+
before_install:
12+
- curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.21.1
13+
- export PATH="$HOME/.yarn/bin:$PATH"

docs/api/options.md

+12-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ These can be passed in an object to `useAsync(options)`, or as props to `<Async
55
- [`promise`](#promise) An already started Promise instance.
66
- [`promiseFn`](#promisefn) Function that returns a Promise, automatically invoked.
77
- [`deferFn`](#deferfn) Function that returns a Promise, manually invoked with `run`.
8+
- [`context`](#context) The first argument for the `promise` and `promiseFn` function.
89
- [`watch`](#watch) Watch a value and automatically reload when it changes.
910
- [`watchFn`](#watchfn) Watch this function and automatically reload when it returns truthy.
1011
- [`initialValue`](#initialvalue) Provide initial data or error for server-side rendering.
@@ -31,17 +32,17 @@ A Promise instance which has already started. It will simply add the necessary r
3132
3233
## `promiseFn`
3334

34-
> `function(props: Object, controller: AbortController): Promise`
35+
> `function(context C, props: AsyncOptions, controller: AbortController): Promise`
3536
3637
A function that returns a promise. It is automatically invoked in `componentDidMount` and `componentDidUpdate`. The function receives all component props \(or options\) and an AbortController instance as arguments.
3738

38-
> Be aware that updating `promiseFn` will trigger it to cancel any pending promise and load the new promise. Passing an inline (arrow) function will cause it to change and reload on every render of the parent component. You can avoid this by defining the `promiseFn` value **outside** of the render method. If you need to pass variables to the `promiseFn`, pass them as additional props to `<Async>`, as `promiseFn` will be invoked with these props. Alternatively you can use `useCallback` or [memoize-one](https://github.com/alexreardon/memoize-one) to avoid unnecessary updates.
39+
> Be aware that updating `promiseFn` will trigger it to cancel any pending promise and load the new promise. Passing an inline (arrow) function will cause it to change and reload on every render of the parent component. You can avoid this by defining the `promiseFn` value **outside** of the render method. If you need to pass variables to the `promiseFn`, pass them via the `context` props of `<Async>`, as `promiseFn` will be invoked with these props. Alternatively you can use `useCallback` or [memoize-one](https://github.com/alexreardon/memoize-one) to avoid unnecessary updates.
3940
4041
## `deferFn`
4142

42-
> `function(args: any[], props: Object, controller: AbortController): Promise`
43+
> `function(context: C, props: AsyncOptions, controller: AbortController): Promise`
4344
44-
A function that returns a promise. This is invoked only by manually calling `run(...args)`. Receives the same arguments as `promiseFn`, as well as any arguments to `run` which are passed through as an array. The `deferFn` is commonly used to send data to the server following a user action, such as submitting a form. You can use this in conjunction with `promiseFn` to fill the form with existing data, then updating it on submit with `deferFn`.
45+
A function that returns a promise. This is invoked only by manually calling `run(param)`. Receives the same arguments as `promiseFn`. The `deferFn` is commonly used to send data to the server following a user action, such as submitting a form. You can use this in conjunction with `promiseFn` to fill the form with existing data, then updating it on submit with `deferFn`.
4546

4647
> Be aware that when using both `promiseFn` and `deferFn`, the shape of their fulfilled value should match, because they both update the same `data`.
4748
@@ -132,3 +133,10 @@ Enables the use of `deferFn` if `true`, or enables the use of `promiseFn` if `fa
132133
> `boolean`
133134
134135
Enables or disables JSON parsing of the response body. By default this is automatically enabled if the `Accept` header is set to `"application/json"`.
136+
137+
138+
## `context`
139+
140+
> `C | undefined`
141+
142+
The argument which is passed as the first argument to the `promiseFn` and the `deferFn`.

docs/getting-started/upgrading.md

+201
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,206 @@
11
# Upgrading
22

3+
## Upgrade to v11
4+
5+
### promiseFn and deferFn unification
6+
7+
The `promiseFn` and the `deferFn` have been unified. They now share the following signature:
8+
9+
```ts
10+
export type AsyncFn<T, C> = (
11+
context: C | undefined,
12+
props: AsyncProps<T, C>,
13+
controller: AbortController
14+
) => Promise<T>
15+
```
16+
17+
Before the `deferFn` and `promiseFn` had this signature:
18+
19+
```ts
20+
export type PromiseFn<T> = (props: AsyncProps<T>, controller: AbortController) => Promise<T>
21+
22+
export type DeferFn<T> = (
23+
args: any[],
24+
props: AsyncProps<T>,
25+
controller: AbortController
26+
) => Promise<T>
27+
```
28+
29+
The difference is the idea of having a `context`, the context will contain all parameters
30+
to `AsyncProps` which are not native to the `AsyncProps`. Before you could pass any parameter
31+
to `AsyncProps` and it would pass them to the `deferFn` and `promiseFn`, now you need to use
32+
the `context` instead.
33+
34+
For example before you could write:
35+
36+
```jsx
37+
useAsync({ promiseFn: loadPlayer, playerId: 1 })
38+
```
39+
40+
Now you must write:
41+
42+
```jsx
43+
useAsync({ promiseFn: loadPlayer, context: { playerId: 1 }})
44+
```
45+
46+
In the above example the context would be `{playerId: 1}`.
47+
48+
This means that `promiseFn` now expects three parameters instead of two.
49+
50+
So before in `< 10.0.0` you would do this:
51+
52+
```jsx
53+
import { useAsync } from "react-async"
54+
55+
// Here loadPlayer has only two arguments
56+
const loadPlayer = async (options, controller) => {
57+
const res = await fetch(`/api/players/${options.playerId}`, { signal: controller.signal })
58+
if (!res.ok) throw new Error(res.statusText)
59+
return res.json()
60+
}
61+
62+
// With hooks
63+
const MyComponent = () => {
64+
const state = useAsync({ promiseFn: loadPlayer, playerId: 1 })
65+
}
66+
67+
// With the Async component
68+
<Async promiseFn={loadPlayer} playerId={1} />
69+
```
70+
71+
In `11.0.0` you need to account for the three parameters:
72+
73+
```jsx
74+
import { useAsync } from "react-async"
75+
76+
// Now it has three arguments
77+
const loadPlayer = async (context, options, controller) => {
78+
const res = await fetch(`/api/players/${context.playerId}`, { signal: controller.signal })
79+
if (!res.ok) throw new Error(res.statusText)
80+
return res.json()
81+
}
82+
83+
// With hooks
84+
const MyComponent = () => {
85+
const state = useAsync({ promiseFn: loadPlayer, context: { playerId: 1 } })
86+
}
87+
88+
// With the Async component
89+
<Async promiseFn={loadPlayer} context={{ playerId: 1 }} />
90+
```
91+
92+
For the `deferFn` this means no longer expecting an array of arguments but instead a singular argument.
93+
The `run` now accepts only one argument which is a singular value. All other arguments to `run` but
94+
the first will be ignored.
95+
96+
So before in `< 10.0.0` you would do this:
97+
98+
```jsx
99+
import Async from "react-async"
100+
101+
const getAttendance = () =>
102+
fetch("/attendance").then(
103+
() => true,
104+
() => false
105+
)
106+
const updateAttendance = ([attend, userId]) =>
107+
fetch(`/attendance/${userId}`, { method: attend ? "POST" : "DELETE" }).then(
108+
() => attend,
109+
() => !attend
110+
)
111+
112+
const userId = 42
113+
114+
const AttendanceToggle = () => (
115+
<Async promiseFn={getAttendance} deferFn={updateAttendance}>
116+
{({ isPending, data: isAttending, run, setData }) => (
117+
<Toggle
118+
on={isAttending}
119+
onClick={() => {
120+
run(!isAttending, userId)
121+
}}
122+
disabled={isPending}
123+
/>
124+
)}
125+
</Async>
126+
)
127+
```
128+
129+
In `11.0.0` you need to account for for the parameters not being an array:
130+
131+
```jsx
132+
import Async from "react-async"
133+
134+
const getAttendance = () =>
135+
fetch("/attendance").then(
136+
() => true,
137+
() => false
138+
)
139+
const updateAttendance = ({ attend, userId }) =>
140+
fetch(`/attendance/${userId}`, { method: attend ? "POST" : "DELETE" }).then(
141+
() => attend,
142+
() => !attend
143+
)
144+
145+
const userId = 42
146+
147+
const AttendanceToggle = () => (
148+
<Async promiseFn={getAttendance} deferFn={updateAttendance}>
149+
{({ isPending, data: isAttending, run, setData }) => (
150+
<Toggle
151+
on={isAttending}
152+
onClick={() => {
153+
run({ attend: isAttending, userId })
154+
}}
155+
disabled={isPending}
156+
/>
157+
)}
158+
</Async>
159+
)
160+
```
161+
162+
### useAsync only accepts one prop
163+
164+
Before in `10.0.0` you could call useAsync with multiple parameters,
165+
the first argument would then be the `promiseFn` like this:
166+
167+
```tsx
168+
const state = useAsync(loadPlayer, { context: { playerId: 1 } })
169+
```
170+
171+
In `11.0.0` there is only one parameter. So the overload no longer works and you need to write this instead:
172+
173+
```tsx
174+
const state = useAsync({ promiseFn: loadPlayer, context: { playerId: 1 } })
175+
```
176+
177+
### WatchFn
178+
179+
Another thing you need to be careful about is the `watchFn` you can no longer count on the fact that
180+
unknown parameters are put into the `AsyncProps`. Before `< 10.0.0` you would write:
181+
182+
```ts
183+
useAsync({
184+
promiseFn,
185+
count: 0,
186+
watchFn: (props, prevProps) => props.count !== prevProps.count
187+
});
188+
```
189+
190+
In `11.0.0` you need to use the `context` instead:
191+
192+
```ts
193+
useAsync({
194+
promiseFn,
195+
context: { count: 0 },
196+
watchFn: (props, prevProps) => props.context.count !== prevProps.context.count
197+
});
198+
```
199+
200+
## Upgrade to v10
201+
202+
This is a major release due to the migration to TypeScript. While technically it shouldn't change anything, it might be a breaking change in certain situations. Theres also a bugfix for watchFn and a fix for legacy browsers.
203+
3204
## Upgrade to v9
4205
5206
The rejection value for failed requests with `useFetch` was changed. Previously it was the Response object. Now it's an

docs/getting-started/usage.md

+11-11
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@ The `useAsync` hook \(available [from React v16.8.0](https://reactjs.org/hooks)\
1010
import { useAsync } from "react-async"
1111

1212
// You can use async/await or any function that returns a Promise
13-
const loadPlayer = async ({ playerId }, { signal }) => {
13+
const loadPlayer = async ({ playerId }, options, { signal }) => {
1414
const res = await fetch(`/api/players/${playerId}`, { signal })
1515
if (!res.ok) throw new Error(res.statusText)
1616
return res.json()
1717
}
1818

1919
const MyComponent = () => {
20-
const { data, error, isPending } = useAsync({ promiseFn: loadPlayer, playerId: 1 })
20+
const { data, error, isPending } = useAsync({ promiseFn: loadPlayer, context: { playerId: 1 } })
2121
if (isPending) return "Loading..."
2222
if (error) return `Something went wrong: ${error.message}`
2323
if (data)
@@ -37,7 +37,7 @@ Or using the shorthand version:
3737

3838
```jsx
3939
const MyComponent = () => {
40-
const { data, error, isPending } = useAsync(loadPlayer, options)
40+
const { data, error, isPending } = useAsync({ promiseFn: loadPlayer, context: { playerId: 1 } })
4141
// ...
4242
}
4343
```
@@ -85,14 +85,14 @@ The classic interface to React Async. Simply use `<Async>` directly in your JSX
8585
import Async from "react-async"
8686

8787
// Your promiseFn receives all props from Async and an AbortController instance
88-
const loadPlayer = async ({ playerId }, { signal }) => {
88+
const loadPlayer = async ({ playerId }, options, { signal }) => {
8989
const res = await fetch(`/api/players/${playerId}`, { signal })
9090
if (!res.ok) throw new Error(res.statusText)
9191
return res.json()
9292
}
9393

9494
const MyComponent = () => (
95-
<Async promiseFn={loadPlayer} playerId={1}>
95+
<Async promiseFn={loadPlayer} context={{ playerId: 1}}>
9696
{({ data, error, isPending }) => {
9797
if (isPending) return "Loading..."
9898
if (error) return `Something went wrong: ${error.message}`
@@ -118,7 +118,7 @@ You can also create your own component instances, allowing you to preconfigure t
118118
```jsx
119119
import { createInstance } from "react-async"
120120

121-
const loadPlayer = async ({ playerId }, { signal }) => {
121+
const loadPlayer = async ({ playerId }, options, { signal }) => {
122122
const res = await fetch(`/api/players/${playerId}`, { signal })
123123
if (!res.ok) throw new Error(res.statusText)
124124
return res.json()
@@ -128,7 +128,7 @@ const loadPlayer = async ({ playerId }, { signal }) => {
128128
const AsyncPlayer = createInstance({ promiseFn: loadPlayer }, "AsyncPlayer")
129129

130130
const MyComponent = () => (
131-
<AsyncPlayer playerId={1}>
131+
<AsyncPlayer context={{playerId: 1}}>
132132
<AsyncPlayer.Fulfilled>{player => `Hello ${player.name}`}</AsyncPlayer.Fulfilled>
133133
</AsyncPlayer>
134134
)
@@ -141,12 +141,12 @@ Several [helper components](usage.md#helper-components) are available to improve
141141
```jsx
142142
import { useAsync, IfPending, IfFulfilled, IfRejected } from "react-async"
143143

144-
const loadPlayer = async ({ playerId }, { signal }) => {
144+
const loadPlayer = async ({ playerId }, options, { signal }) => {
145145
// ...
146146
}
147147

148148
const MyComponent = () => {
149-
const state = useAsync({ promiseFn: loadPlayer, playerId: 1 })
149+
const state = useAsync({ promiseFn: loadPlayer, context: { playerId: 1 } })
150150
return (
151151
<>
152152
<IfPending state={state}>Loading...</IfPending>
@@ -171,14 +171,14 @@ Each of the helper components are also available as static properties of `<Async
171171
```jsx
172172
import Async from "react-async"
173173

174-
const loadPlayer = async ({ playerId }, { signal }) => {
174+
const loadPlayer = async ({ playerId }, options, { signal }) => {
175175
const res = await fetch(`/api/players/${playerId}`, { signal })
176176
if (!res.ok) throw new Error(res.statusText)
177177
return res.json()
178178
}
179179

180180
const MyComponent = () => (
181-
<Async promiseFn={loadPlayer} playerId={1}>
181+
<Async promiseFn={loadPlayer} context={{playerId: 1 }}>
182182
<Async.Pending>Loading...</Async.Pending>
183183
<Async.Fulfilled>
184184
{data => (

docs/guide/async-actions.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ automatically invoked by React Async when rendering the component. Instead it wi
1212
import React, { useState } from "react"
1313
import { useAsync } from "react-async"
1414

15-
const subscribe = ([email], props, { signal }) =>
15+
const subscribe = ({email}, options, { signal }) =>
1616
fetch("/newsletter", { method: "POST", body: JSON.stringify({ email }), signal })
1717

1818
const NewsletterForm = () => {
@@ -21,7 +21,7 @@ const NewsletterForm = () => {
2121

2222
const handleSubmit = event => {
2323
event.preventDefault()
24-
run(email)
24+
run({email})
2525
}
2626

2727
return (
@@ -36,11 +36,11 @@ const NewsletterForm = () => {
3636
}
3737
```
3838

39-
As you can see, the `deferFn` is invoked with 3 arguments: `args`, `props` and the AbortController. `args` is an array
39+
As you can see, the `deferFn` is invoked with 3 arguments: `context`, `props` and the AbortController. `context` is an object
4040
representing the arguments that were passed to `run`. In this case we passed the `email`, so we can extract that from
41-
the `args` array at the first index using [array destructuring] and pass it along to our `fetch` request.
41+
the `context` prop using [object destructuring] and pass it along to our `fetch` request.
4242

43-
[array destructuring]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring
43+
[object destructuring]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
4444

4545
## Sending data with `useFetch`
4646

0 commit comments

Comments
 (0)