I'm a very beginner on React, i'm trying to refactor a ES5 class to ES6 class by comparing with my app's courses file. Everything was runing ok until this line:
if (scrolledToBottom) {
this.querySearchResult();
}
here is a error messagem on the console when the user scroll to the page's botton:
• Console's message:
TypeError: this.querySearchResult is not a function handleOnScroll
if (scrolledToBottom) {
> 81 | this.querySearchResult(); // This line results the error
82 | }
83 | }
• Complete Code:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
export default class InfiniteData extends Component {
constructor(props) {
super(props);
this.state = {data: ""};
}
getInitialState() {
return ({data: [], requestSent: false});
}
componentDidMount() {
window.addEventListener('scroll', this.handleOnScroll);
this.initFakeData();
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleOnScroll);
}
initFakeData() {
var data = this.createFakeData(this.state.data.length, 100);
this.setState({data: data});
}
createFakeData(startKey, counter) {
var i = 0;
var data = [];
for (i = 0; i < counter; i++) {
var fakeData = (<div key={startKey+i} className="data-info">Fake Data {startKey+i}</div>);
data.push(fakeData);
}
return data;
}
querySearchResult() {
if (this.state.requestSent) {
return;
}
// enumerate a slow query
setTimeout(this.doQuery, 2000);
this.setState({requestSent: true});
}
doQuery() {
// use jQuery
$.ajax({
url: "#",
data: null,
method: "GET",
success: function(data, textStatus, jqXHR) {
var fakeData = this.createFakeData(this.state.data.length, 20);
var newData = this.state.data.concat(fakeData);
this.setState({data: newData, requestSent: false});
}.bind(this),
error: function(jqXHR, textStatus, errorThrown) {
this.setState({requestSent: false});
}.bind(this)
});
}
handleOnScroll() {
// http://stackoverflow.com/questions/9439725/javascript-how-to-detect-if-browser-window-is-scrolled-to-bottom
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
var clientHeight = document.documentElement.clientHeight || window.innerHeight;
var scrolledToBottom = Math.ceil(scrollTop + clientHeight) >= scrollHeight;
if (scrolledToBottom) {
this.querySearchResult();
}
}
render() {
return (
<div>
<div className="data-container">
{this.state.data}
</div>
{(() => {
if (this.state.requestSent) {
return(
<div className="data-loading">
<i className="fa fa-refresh fa-spin"></i>
</div>
);
} else {
return(
<div className="data-loading"></div>
);
}
})()}
</div>
);
}
};