clauderic / clauderic/react-tiny-virtual-list
setState in onItemsRendered
- Dominant language
- TypeScript
- Stars
- 2.5k
- Forks
- 159
- PR merge metrics
- No merged PRs in 30d
Description
I need to keep track of which items are visible outside of the `VirtualList` component. However, if I call `setState` in `onItemsRendered`, then React will correctly complain:
```
Warning: Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
```
Is there are correct pattern for this? Ideally VirtualList would have a renderProp style prop that could look like `({ RenderedListNode, startIndex, endIndex}) => Node`.
This is the code, it works in this simple example but causes the React warning and issues in more complicated code:
```
// @flow
import React from "react";
import VirtualList from "react-tiny-virtual-list";
const data = Array(1000)
.fill(0)
.map((item, index) => index);
type Props = {};
type State = {
currentlyVisibleIndex: number,
};
class Test extends React.Component {
state = { currentlyVisibleIndex: 0 };
onItemsRendered = ({ startIndex, stopIndex }) => {
const { currentlyVisibleIndex } = this.state;
if (currentlyVisibleIndex !== startIndex) {
this.setState({ currentlyVisibleIndex: startIndex });
}
};
render() {
const { currentlyVisibleIndex } = this.state;
return (
(
{data[index]}, Row: #{index}
)}
onItemsRendered={this.onItemsRendered}
/>
);
}
}
export default Test;
```
Contributor guide
Assessment
This issue has not been assessed yet.