Skip to content

Commit

Permalink
fix(use-masonry): should update when positioner changes (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
V3RON committed Apr 28, 2022
1 parent e0d8c7a commit 55cc606
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
54 changes: 54 additions & 0 deletions src/index.test.tsx
@@ -1,6 +1,7 @@
import { dimension } from "@shopify/jest-dom-mocks";
import { act, render, screen } from "@testing-library/react";
import { act as hookAct, renderHook } from "@testing-library/react-hooks";
import type { RenderHookResult } from "@testing-library/react-hooks";
import * as React from "react";
import {
createResizeObserver,
Expand All @@ -14,6 +15,7 @@ import {
useResizeObserver,
useScroller,
} from "./index";
import * as useForceUpdateModule from "./use-force-update";

jest.useFakeTimers();

Expand Down Expand Up @@ -50,6 +52,7 @@ afterEach(() => {
resetScroll();
dimension.restore();
perf.uninstall();
jest.restoreAllMocks();
});

describe("useMasonry()", () => {
Expand Down Expand Up @@ -312,6 +315,57 @@ describe("useMasonry()", () => {
const { result } = renderBasicMasonry({ className: "foo" });
expect(result.current.props.className).toEqual("foo");
});

it('should render multiple batches if "itemHeightEstimate" isn\'t accurate', () => {
// eslint-disable-next-line prefer-const
let hook: RenderHookResult<
{ items: { id: number; height: number }[] },
JSX.Element
>;

// Render hook again on useForceUpdate
jest.spyOn(useForceUpdateModule, "useForceUpdate").mockReturnValue(() => {
if (hook) {
hook.rerender();
render(hook.result.current);
}
});

// Render hook with items-dependent positioner
hook = renderHook(
(props) => {
const positioner = usePositioner({ width: 1280, columnWidth: 1280 }, [
props.items[0],
]);
return useMasonry({
height: 1280,
positioner,
itemHeightEstimate: 640,
overscanBy: 1,
render: FakeCard,
scrollTop: 0,
...props,
});
},
{
initialProps: {
items: getFakeItems(100, 80),
},
}
);

// Switch items, positioner will update itself
hook.rerender({
items: getFakeItems(100, 80),
});

// All items should have measured styles
for (let i = 0; i < 2; i++) {
expect(hook.result.current.props.children[i].props.style).not.toEqual(
prerenderStyles(1280)
);
}
});
});

describe("usePositioner()", () => {
Expand Down
2 changes: 1 addition & 1 deletion src/use-masonry.tsx
Expand Up @@ -187,7 +187,7 @@ export function useMasonry<Item>({
React.useEffect(() => {
if (needsFreshBatch) forceUpdate();
// eslint-disable-next-line
}, [needsFreshBatch]);
}, [needsFreshBatch, positioner]);

// gets the container style object based upon the estimated height and whether or not
// the page is being scrolled
Expand Down

0 comments on commit 55cc606

Please sign in to comment.