useLockFn
A hook to lock a function until the previous promise is resolved
Installation
npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-lock-fn.json"pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-lock-fn.json"yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-lock-fn.json"bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-lock-fn.json"Copy and paste the following code into your project.
import { useCallback, useRef } from 'react'
export function useLockFn<P extends any[] = any[], V = any>(
fn: (...args: P) => Promise<V>,
) {
const lockRef = useRef(false)
return useCallback(
async (...args: P) => {
if (lockRef.current) {
return
}
lockRef.current = true
try {
return await fn(...args)
} finally {
lockRef.current = false
}
},
[fn],
)
}API
/**
* A hook to lock a function until the previous promise is resolved
* @param fn - The function to lock
* @returns The locked function
*/
export function useLockFn<P extends any[] = any[], V = any>(
fn: (...args: P) => Promise<V>,
): (...args: P) => Promise<V | undefined>Last updated on