Skip to content

Commit

Permalink
fix: useFunction
Browse files Browse the repository at this point in the history
  • Loading branch information
hemengke1997 committed Jul 9, 2021
1 parent fa65e33 commit cc4df33
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 16 deletions.
23 changes: 15 additions & 8 deletions src/utils/useFunction.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import React from 'react';
import { useRef } from 'react';

function useFunction<T extends (...args: any[]) => any>(fn: T) {
const ref = React.useRef<Function>(() => {
throw new Error('Cannot call function while rendering.');
});
export type noop = (...args: any[]) => any;

ref.current = fn;
function usePersistFn<T extends noop>(fn: T) {
const fnRef = useRef<T>(fn);
fnRef.current = fn;

return React.useCallback(ref.current as T, [ref]);
const persistFn = useRef<T>();
if (!persistFn.current) {
persistFn.current = function (...args) {
// eslint-disable-next-line @typescript-eslint/no-invalid-this
return fnRef.current!.apply(this, args);
} as T;
}

return persistFn.current!;
}

export default useFunction;
export default usePersistFn;
15 changes: 8 additions & 7 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
{
"compilerOptions": {
"outDir": "dist",
"target": "ESNext",
"lib": [
"DOM",
"ESNext"
],
"allowJs": false,
"skipLibCheck": false,
"declaration": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"forceConsistentCasingInFileNames": true,
Expand All @@ -22,7 +15,15 @@
"noEmit": true,
"jsx": "react-jsx",
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"declaration": false,
"strictNullChecks": true,
"target": "ES5",
"allowJs": true,
"esModuleInterop": true,
"downlevelIteration": true,
"sourceMap": true,
},
"include": [
"src/**/*",
Expand Down
3 changes: 2 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ export default defineConfig({
reactRefresh(),
{
...typescript2({
check: true,
check: false,
tsconfig: path.resolve(__dirname, `tsconfig.json`),
tsconfigOverride: {
compilerOptions: {
sourceMap: false,
declaration: true,
declarationMap: false,
allowJs: false
},
include: ['src/**/*'],
},
Expand Down

0 comments on commit cc4df33

Please sign in to comment.