I am trying to add infinite scroll to my page. Whenever the user scrolls down the page it will call in a jSon that will update the array responsible of showing messages and therefore load new messages.
However if i reach the bottom of the page it will call new messages if i go either up or down with the scroll instead of acting as i intended.
No error messages are shown but i am not really sure why this happens.
The code was based on what I've found here link and the code below is what i have now.
class Messages extends React.Component {
constructor(props) {
super(props);
this.state = {
messagesList: [],
messageCount: 0,
totalMessages: 0,
};
}
isBottom = el => el.getBoundingClientRect().bottom <= window.innerHeight;
componentDidMount() {
document.addEventListener('scroll', this.trackScrolling);
}
trackScrolling = () => {
const wrappedElement = document.getElementById("header");
// The if statement bellow checks if the i am at the bottom of the page and if i have more messages to load, the second information comes in the json
if (this.isBottom(wrappedElement) != null && this.state.messageCount <= this.state.totalMessages) {
fetchAllMessages(10, this.state.messageCount)
.then(({ response }) => {
this.setState({
messagesList: this.state.messagesList.concat(response.messages.content),
messageCount: this.state.messageCount + 1,
});
})
.catch(() => null);
document.removeEventListener('scroll', this.trackScrolling);
}
};
componentWillMount() {
fetchAllMessage(10, this.state.messageCount)
.then(({ response }) => {
this.setState({
messageList: response.message.content,
totalMessage: response.message.totalMessage,
messageCount: this.state.messageCount + 1,
});
})
.catch(() => null);
}
render() {
return (
<div>
// Adds the event listener again
{document.addEventListener('scroll', this.trackScrolling)}
<Canvas >
<Title >Messages</Title>
{this.state.messagesList.map(i => (
<Card id={"header"}>
<CardContent>
<div>
<div className={`icon ${MessageType[i.type].class}`} /> // adds an image
</div>
<div className="cardText" >
<Markdown>
{`${i.message} ${i.date != null ? ` on : ${i.date}` : ''}`}
</Markdown>
</div>
</CardContent>
</Card>
))}
</Canvas>
</div>
);
}
}
export default Messages;
I believe it might be something related to either window.innerHeight or the the fact i reset the scroll listener but i am not really sure.