Skip to content

Commit

Permalink
fix(useLockFn): ensure the stability of the output function reference…
Browse files Browse the repository at this point in the history
…s of useLockFn
  • Loading branch information
wupanyan committed Jul 31, 2023
1 parent 5b056d0 commit 284d59a
Showing 1 changed file with 13 additions and 16 deletions.
29 changes: 13 additions & 16 deletions packages/hooks/src/useLockFn/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
import { useRef, useCallback } from 'react';

import useMemoizedFn from '../useMemoizedFn';
function useLockFn<P extends any[] = any[], V extends any = any>(fn: (...args: P) => Promise<V>) {
const lockRef = useRef(false);

return useCallback(
async (...args: P) => {
if (lockRef.current) return;
lockRef.current = true;
try {
const ret = await fn(...args);
lockRef.current = false;
return ret;
} catch (e) {
lockRef.current = false;
throw e;
}
},
[fn],
);
return useMemoizedFn(async (...args: P) => {
if (lockRef.current) return;
lockRef.current = true;
try {
const ret = await fn(...args);
lockRef.current = false;
return ret;
} catch (e) {
lockRef.current = false;
throw e;
}
});
}

export default useLockFn;

0 comments on commit 284d59a

Please sign in to comment.