File tree Expand file tree Collapse file tree 5 files changed +66
-3
lines changed Expand file tree Collapse file tree 5 files changed +66
-3
lines changed Original file line number Diff line number Diff line change 1
1
{
2
2
"name" : " http-react" ,
3
- "version" : " 3.0.6 " ,
3
+ "version" : " 3.1.0 " ,
4
4
"description" : " React hooks for data fetching" ,
5
5
"main" : " dist/index.js" ,
6
6
"scripts" : {
Original file line number Diff line number Diff line change @@ -36,5 +36,6 @@ export {
36
36
useReFetch ,
37
37
useRevalidating ,
38
38
useSuccess ,
39
- useDebounceFetch
39
+ useDebounceFetch ,
40
+ createActionsHook
40
41
} from './others'
Original file line number Diff line number Diff line change @@ -636,3 +636,41 @@ export function useImperative() {
636
636
637
637
return imperativeFetch
638
638
}
639
+
640
+ export const createActionsHook = < Acts > ( cfg ?: FetchInit ) =>
641
+ function useServerAction < T = any > (
642
+ actionName : keyof Acts ,
643
+ otherConfig ?: FetchInit < T >
644
+ ) {
645
+ type K = keyof Acts
646
+ const [ args , setArgs ] = React . useState < any > ( )
647
+
648
+ const { reFetch, ...other } = useFetch < T > ( '/[action]' , {
649
+ baseUrl : '/api/actions' ,
650
+ method : 'POST' ,
651
+ id : {
652
+ __ACTION_EXECUTION__ : actionName
653
+ } ,
654
+ params : {
655
+ action : actionName
656
+ } ,
657
+ body : args ?. args || { } ,
658
+ query : args ?. search || { } ,
659
+ auto : false ,
660
+ ...cfg ,
661
+ ...otherConfig
662
+ } )
663
+
664
+ return {
665
+ ...other ,
666
+ execute ( params : Acts [ K ] , searchParams ?: any ) {
667
+ setArgs ( {
668
+ args : params ,
669
+ search : searchParams
670
+ } )
671
+ setTimeout ( ( ) => {
672
+ reFetch ( )
673
+ } , 0 )
674
+ }
675
+ }
676
+ }
Original file line number Diff line number Diff line change @@ -47,7 +47,8 @@ export {
47
47
useReFetch ,
48
48
useRevalidating ,
49
49
useSuccess ,
50
- useDebounceFetch
50
+ useDebounceFetch ,
51
+ createActionsHook
51
52
} from './hooks'
52
53
53
54
export { FetchConfig , SSRSuspense } from './components/server'
@@ -72,3 +73,5 @@ export {
72
73
serialize ,
73
74
notNull
74
75
} from './utils/shared'
76
+
77
+ export { createActionHandler } from './server'
Original file line number Diff line number Diff line change
1
+ export function createActionHandler < ActionTypes > ( actions : {
2
+ [ e in keyof ActionTypes ] : (
3
+ req : Request ,
4
+ args : ActionTypes [ e ] ,
5
+ searchParams : URLSearchParams
6
+ ) => any
7
+ } ) {
8
+ return async (
9
+ req : Request ,
10
+ params : {
11
+ params : {
12
+ action : keyof ActionTypes
13
+ }
14
+ }
15
+ ) =>
16
+ actions [ params . params . action ] (
17
+ req ,
18
+ await req . json ( ) ,
19
+ new URL ( req . url ) . searchParams
20
+ )
21
+ }
You can’t perform that action at this time.
0 commit comments