-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
584 additions
and
1,529 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import {useState, useEffect, useTransition, useRef} from "react" | ||
import {useBoolean} from "usehooks-ts" | ||
|
||
/** | ||
* Call a server action and provide a pending state while the process is running. | ||
* | ||
* @see https://github.com/vercel/next.js/discussions/51371#discussioncomment-8671340 | ||
* | ||
* @param action | ||
* @param onFinished | ||
*/ | ||
const useServerAction = <P extends any[], R>(action?: (..._args: P) => Promise<R>, onFinished?: (_: R | undefined) => void): [(..._args: P) => Promise<R | undefined>, boolean] => { | ||
const [isPending, startTransition] = useTransition() | ||
const [result, setResult] = useState<R>() | ||
const {value: finished, setTrue: setFinished} = useBoolean(false) | ||
const resolver = useRef<(_value?: R | PromiseLike<R>) => void>() | ||
|
||
useEffect(() => { | ||
if (!finished) return | ||
|
||
if (onFinished) onFinished(result) | ||
resolver.current?.(result) | ||
}, [result, finished, onFinished]) | ||
|
||
const runAction = async (...args: P): Promise<R | undefined> => { | ||
startTransition(() => { | ||
if (action) { | ||
action(...args).then(data => { | ||
setResult(data) | ||
setFinished() | ||
}) | ||
} | ||
}) | ||
|
||
return new Promise(resolve => { | ||
resolver.current = resolve | ||
}) | ||
} | ||
|
||
return [runAction, isPending] | ||
} | ||
|
||
export default useServerAction |
Oops, something went wrong.