Skip to content

Commit

Permalink
feat: trigger mount when window resize
Browse files Browse the repository at this point in the history
  • Loading branch information
hemengke1997 committed Jul 9, 2021
1 parent 73ded3d commit 017aeab
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 2 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
"react": ">=16.8.0"
},
"dependencies": {
"@types/lodash.debounce": "^4.0.6",
"classnames": "^2.3.1",
"lodash.debounce": "^4.0.8",
"lodash.throttle": "^4.1.1",
"react": "^17.0.0",
"react-dom": "^17.0.0",
Expand Down
12 changes: 10 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import { useRef } from 'react';
import ResizableHeader from './ResizableHeader';
import useDebounceFn from './utils/useDebounceFn';
import useFunction from './utils/useFunction';

function useTableResizableHeader<ColumnType extends Record<string, any>>(
Expand Down Expand Up @@ -42,6 +43,17 @@ function useTableResizableHeader<ColumnType extends Record<string, any>>(
triggerMount.current += 1;
}, [columns]);

const { run: onWindowResize } = useDebounceFn(() => {
triggerMount.current += 1;
});

React.useEffect(() => {
window.addEventListener('resize', onWindowResize);
return () => {
window.removeEventListener('resize', onWindowResize);
};
}, []);

React.useEffect(() => {
const width = resizableColumns.reduce((total, current) => {
return total + (Number(current.width) || defaultWidth);
Expand Down
42 changes: 42 additions & 0 deletions src/utils/useDebounceFn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import debounce from 'lodash.debounce';
import { useRef, useEffect } from 'react';
import useCreation from './useCreation';

type Fn = (...args: any) => any;

export interface DebounceOptions {
wait?: number;
leading?: boolean;
trailing?: boolean;
}

function useDebounceFn<T extends Fn>(fn: T, options?: DebounceOptions) {
const fnRef = useRef<T>(fn);
fnRef.current = fn;

const wait = options?.wait ?? 1000;

const debounced = useCreation(
() =>
debounce<T>(
((...args: any[]) => {
return fnRef.current(...args);
}) as T,
wait,
options,
),
[],
);

useEffect(() => {
debounced.cancel();
}, []);

return {
run: debounced as unknown as T,
cancel: debounced.cancel,
flush: debounced.flush,
};
}

export default useDebounceFn;

0 comments on commit 017aeab

Please sign in to comment.