Skip to content

Commit efa9b20

Browse files
authored
Merge pull request #163 from atomic-state/feat-small-rpc
feat(rpc):
2 parents 6c8b313 + d24ff07 commit efa9b20

File tree

5 files changed

+66
-3
lines changed

5 files changed

+66
-3
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "http-react",
3-
"version": "3.0.6",
3+
"version": "3.1.0",
44
"description": "React hooks for data fetching",
55
"main": "dist/index.js",
66
"scripts": {

src/hooks/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,6 @@ export {
3636
useReFetch,
3737
useRevalidating,
3838
useSuccess,
39-
useDebounceFetch
39+
useDebounceFetch,
40+
createActionsHook
4041
} from './others'

src/hooks/others.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,3 +636,41 @@ export function useImperative() {
636636

637637
return imperativeFetch
638638
}
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+
}

src/index.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ export {
4747
useReFetch,
4848
useRevalidating,
4949
useSuccess,
50-
useDebounceFetch
50+
useDebounceFetch,
51+
createActionsHook
5152
} from './hooks'
5253

5354
export { FetchConfig, SSRSuspense } from './components/server'
@@ -72,3 +73,5 @@ export {
7273
serialize,
7374
notNull
7475
} from './utils/shared'
76+
77+
export { createActionHandler } from './server'

src/server/index.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
}

0 commit comments

Comments
 (0)