clauderic / clauderic/react-tiny-virtual-list

setState in onItemsRendered

Open
#57 1 comment 0 reactions 0 assignees View on GitHub
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 (


Currently Visible: {currentlyVisibleIndex}

(

{data[index]}, Row: #{index}

)}
onItemsRendered={this.onItemsRendered}
/>

);
}
}

export default Test;
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.