Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "http-react",
"version": "3.0.6",
"version": "3.1.0",
"description": "React hooks for data fetching",
"main": "dist/index.js",
"scripts": {
Expand Down
3 changes: 2 additions & 1 deletion src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,6 @@ export {
useReFetch,
useRevalidating,
useSuccess,
useDebounceFetch
useDebounceFetch,
createActionsHook
} from './others'
38 changes: 38 additions & 0 deletions src/hooks/others.ts
Original file line number Diff line number Diff line change
Expand Up @@ -636,3 +636,41 @@ export function useImperative() {

return imperativeFetch
}

export const createActionsHook = <Acts>(cfg?: FetchInit) =>
function useServerAction<T = any>(
actionName: keyof Acts,
otherConfig?: FetchInit<T>
) {
type K = keyof Acts
const [args, setArgs] = React.useState<any>()

const { reFetch, ...other } = useFetch<T>('/[action]', {
baseUrl: '/api/actions',
method: 'POST',
id: {
__ACTION_EXECUTION__: actionName
},
params: {
action: actionName
},
body: args?.args || {},
query: args?.search || {},
auto: false,
...cfg,
...otherConfig
})

return {
...other,
execute(params: Acts[K], searchParams?: any) {
setArgs({
args: params,
search: searchParams
})
setTimeout(() => {
reFetch()
}, 0)
}
}
}
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ export {
useReFetch,
useRevalidating,
useSuccess,
useDebounceFetch
useDebounceFetch,
createActionsHook
} from './hooks'

export { FetchConfig, SSRSuspense } from './components/server'
Expand All @@ -72,3 +73,5 @@ export {
serialize,
notNull
} from './utils/shared'

export { createActionHandler } from './server'
21 changes: 21 additions & 0 deletions src/server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export function createActionHandler<ActionTypes>(actions: {
[e in keyof ActionTypes]: (
req: Request,
args: ActionTypes[e],
searchParams: URLSearchParams
) => any
}) {
return async (
req: Request,
params: {
params: {
action: keyof ActionTypes
}
}
) =>
actions[params.params.action](
req,
await req.json(),
new URL(req.url).searchParams
)
}