I have a chat screen on my app that will initially display messages at the bottom of a div, and as a user scrolls up, more messages will be fetched. I am using the react-infinite-scroll-component
package to handle the infinite scrolling.
To illustrate this issue, I created and edited an example from online, using simple divs to replicate chat messages.
The code below should fetch some data(dummy data in this example), after a user scrolls up the div. However instead, no data is being fetched as a user scrolls up, and only the original data(the initial state) is being displayed.
Here is the code snippet:
import React from "react";
import { render } from "react-dom";
import InfiniteScroll from "react-infinite-scroll-component";
const style = {
height: 30,
border: "1px solid green",
margin: 6,
padding: 8
};
class App extends React.Component {
state = {
items: Array.from({ length: 20 })
};
fetchMoreData = () => {
console.log('Fetch called')
this.setState({
items: this.state.items.concat(Array.from({ length: 30 }))
});
}
render() {
return (
<div
id="scrollableDiv"
style={{
height: 300,
overflow: "auto",
display: "flex",
flexDirection: "column-reverse"
}}
>
{/*Put the scroll bar always on the bottom*/}
<InfiniteScroll
dataLength={this.state.items.length}
next={this.fetchMoreData}
style={{ display: "flex", flexDirection: "column-reverse" }} //To put endMessage and loader to the top.
inverse={true} //
hasMore={true}
loader={<h4>Loading...</h4>}
scrollableTarget="scrollableDiv"
>
{this.state.items.map((_, index) => (
<div style={style} key={index}>
div - #{index}
</div>
))}
</InfiniteScroll>
</div>
);
}
}
render(<App />, document.getElementById("root"));
Here is the place where I got the code from: https://codesandbox.io/s/trusting-pond-6l6x5y?file=/src/index.js
In the example, once the user reaches the top of the container, fetch is not being called. However I would like it so that when the user has scrolled to the top of the div, fetch is called.
Currently, only the last item of the initial state is displayed at the top of the container. I would like the user to be able to continue to scroll, and subsequently, the fetch method will be called.
Also note that the console.log(‘Fetch called’) within fetchMoreData
is never being logged to the console. Is there anything missing from the code that could be causing this issue?
2
Answers
How about check react version.
I guess you copied this sample and tried.
Please try this code. The hasMore value should be regulated or the fetchMoreData function will be called indefinitely.
https://codesandbox.io/s/sweet-fire-62xhpj?file=/src/index.js