Skip to content

Commit 5ad256d

Browse files
committed
Add usePaginationRequest hook
1 parent 19d1d93 commit 5ad256d

File tree

4 files changed

+75
-1
lines changed

4 files changed

+75
-1
lines changed

README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,31 @@ export const Sender = () => {
116116

117117
```
118118

119+
### `useFetch`
120+
```javascript
121+
usePromise<T, I: $ReadOnlyArray<mixed>>(
122+
callFunction: ?(...args: I) => Promise<T>,
123+
...inputs: I
124+
): TUsePromiseResult<T>
125+
```
126+
where `TUsePromiseResult<T>` is
127+
```javascript
128+
type TUsePromiseResult<T> = {
129+
data: ?T,
130+
isLoading: boolean,
131+
error: mixed
132+
}
133+
```
134+
135+
### `usePaginatedRequest`
136+
Create a paginated request.
137+
```javascript
138+
usePaginatedRequest = <T>(
139+
request: (params: { limit: number, offset: number }) => Promise<Array<T>>,
140+
limit: number
141+
): {
142+
data: Array<T>,
143+
loadMore?: () => mixed,
144+
hasMore: boolean
145+
};
146+
```

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-fetch-hook",
3-
"version": "1.3.5",
3+
"version": "1.4.0",
44
"description": "React fetch hook",
55
"main": "./dist/index.js",
66
"scripts": {

src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22

33
export { useFetch } from "./useFetch";
44
export { usePromise } from "./usePromise";
5+
export { usePaginatedRequest } from "./usePaginatedRequest";

src/usePaginatedRequest.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// @flow
2+
import { useState, useRef, useEffect } from "react";
3+
4+
export const usePaginatedRequest = <T>(
5+
request: (params: { limit: number, offset: number }) => Promise<Array<T>>,
6+
limit: number
7+
): {
8+
data: Array<T>,
9+
loadMore?: () => mixed,
10+
hasMore: boolean
11+
} => {
12+
const [data, setData] = useState([]);
13+
const currentUpdate = useRef();
14+
const [offset, setOffset] = useState(0);
15+
const [hasMore, setHasMore] = useState(true);
16+
17+
const loadMoreRef = useRef(() => {});
18+
19+
useEffect(
20+
() => {
21+
loadMoreRef.current = async () => {
22+
if (currentUpdate.current) {
23+
await currentUpdate.current;
24+
}
25+
if (hasMore) {
26+
setOffset(offset + limit);
27+
}
28+
};
29+
30+
const update = async () => {
31+
const result = await request({ limit, offset });
32+
setHasMore(result.length === limit);
33+
setData(prev => [...prev, ...result]);
34+
};
35+
currentUpdate.current = update();
36+
},
37+
[offset]
38+
);
39+
40+
return {
41+
data,
42+
loadMore: loadMoreRef.current || (() => {}),
43+
hasMore
44+
};
45+
};

0 commit comments

Comments
 (0)