Skip to content

Commit 088d533

Browse files
author
Karl Johansson
committed
Throw an error when the dataLength prop is missing
Previously, missing the mandatory dataLength prop resulted in the component silently failing to add more content. This commit makes the issue more visible, as the component will now throw an error after mounting if the dataLength prop isn't provided.
1 parent 6d64b4e commit 088d533

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

src/__tests__/index.test.tsx

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,12 @@ import { render, cleanup } from '@testing-library/react';
33
import InfiniteScroll from '../index';
44

55
describe('React Infinite Scroll Component', () => {
6-
afterEach(cleanup);
6+
const originalConsoleError = console.error;
7+
8+
afterEach(() => {
9+
cleanup();
10+
console.error = originalConsoleError;
11+
});
712

813
it('renders .infinite-scroll-component', () => {
914
const { container } = render(
@@ -78,6 +83,18 @@ describe('React Infinite Scroll Component', () => {
7883
expect(onScrollMock).toHaveBeenCalled();
7984
});
8085

86+
describe('When missing the dataLength prop', () => {
87+
it('throws an error', () => {
88+
console.error = jest.fn();
89+
const props = { loader: 'Loading...', hasMore: false, next: (() => {}) }
90+
91+
// @ts-ignore
92+
expect(() => render(<InfiniteScroll {...props} />)).toThrow(Error)
93+
// @ts-ignore
94+
expect(console.error.mock.calls[0][0]).toContain('"dataLength" is missing')
95+
});
96+
})
97+
8198
describe('When user scrolls to the bottom', () => {
8299
it('does not show loader if hasMore is false', () => {
83100
const { container, queryByText } = render(

src/index.tsx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,13 @@ export default class InfiniteScroll extends Component<Props, State> {
6666
private maxPullDownDistance = 0;
6767

6868
componentDidMount() {
69+
if (typeof this.props.dataLength === 'undefined') {
70+
throw new Error(
71+
`mandatory prop "dataLength" is missing. The prop is needed` +
72+
` when loading more content. Check README.md for usage`
73+
)
74+
}
75+
6976
this._scrollableNode = this.getScrollableTarget();
7077
this.el = this.props.height
7178
? this._infScroll

0 commit comments

Comments
 (0)