File tree Expand file tree Collapse file tree 4 files changed +75
-1
lines changed Expand file tree Collapse file tree 4 files changed +75
-1
lines changed Original file line number Diff line number Diff 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+ ```
Original file line number Diff line number Diff line change 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" : {
Original file line number Diff line number Diff line change 22
33export { useFetch } from "./useFetch" ;
44export { usePromise } from "./usePromise" ;
5+ export { usePaginatedRequest } from "./usePaginatedRequest" ;
Original file line number Diff line number Diff line change 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+ } ;
You can’t perform that action at this time.
0 commit comments