Skip to content

Commit

Permalink
fix: add default value for useSize (#2057)
Browse files Browse the repository at this point in the history
* fix: add default value for useSize

* test: update test

* test: update test

* fix: update type
  • Loading branch information
li-jia-nan committed Feb 19, 2023
1 parent 4d82a07 commit f3ecb7d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 10 deletions.
6 changes: 4 additions & 2 deletions packages/hooks/src/useSize/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ jest.mock('resize-observer-polyfill', () => {
describe('useSize', () => {
it('with argument', () => {
const hook = renderHook(() => useSize(document.body));
expect(hook.result.current).toBeUndefined();
expect(hook.result.current).toEqual({ height: 0, width: 0 });
});

it('should not work when target is null', () => {
renderHook(() => useSize(null));
expect(() => {
renderHook(() => useSize(null));
}).not.toThrowError();
});

it('should work', () => {
Expand Down
13 changes: 5 additions & 8 deletions packages/hooks/src/useSize/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,23 @@ import useIsomorphicLayoutEffectWithTarget from '../utils/useIsomorphicLayoutEff
type Size = { width: number; height: number };

function useSize(target: BasicTarget): Size | undefined {
const [state, setState] = useRafState<Size>();
const el = getTargetElement(target);
const [state, setState] = useRafState<Size | undefined>(
el ? { width: el.clientWidth, height: el.clientHeight } : undefined,
);

useIsomorphicLayoutEffectWithTarget(
() => {
const el = getTargetElement(target);

if (!el) {
return;
}

const resizeObserver = new ResizeObserver((entries) => {
entries.forEach((entry) => {
const { clientWidth, clientHeight } = entry.target;
setState({
width: clientWidth,
height: clientHeight,
});
setState({ width: clientWidth, height: clientHeight });
});
});

resizeObserver.observe(el);
return () => {
resizeObserver.disconnect();
Expand Down

0 comments on commit f3ecb7d

Please sign in to comment.