Reputation: 101
This is my post-card page(only the specific part) where i am displaying data from fetched Api.
fetchMoreData(){
this.setState({
index: this.state.index + 5
})
}
componentDidMount(){
window.addEventListener('scroll', this.onScroll);
this.fetchMoreData();
}
onScroll = () => {
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
this.fetchMoreData();
}
});
}
As My API is a testing API i fetch all the data in my posts page and then pass it to my post-card page so on change of this.state.index it displays more item.
The issue I am facing is that I get an error that this.fetchMoreData() is not a function. Feel free to point out any mistakes.
Upvotes: 2
Views: 5888
Reputation: 4889
onScroll = () => {
$(window).scroll(() => {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
this.fetchMoreData();
}
});
}
If you use function
it will be called in the context of the window
object (in your case). You can use closures to save parent context, like this:
onScroll = () => {
const that = this;
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
that.fetchMoreData();
}
});
};
But arrow functions bind this
argument to that of the parent scope, so this
will link to your component class. And it is much elegant and easier solution than using of function
, especially you already using arrow functions in your component.
Upvotes: 1
Reputation: 1668
you can use es6 arrow function because because you need to bind this value from function to our class. so this won't work $(window).scroll(function() {
. so you can u do like this.
$(window).scroll(() => {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
this.fetchMoreData();
}
});
Upvotes: 1
Reputation: 2111
Make fetchMoreData
an arrow function just like onScroll
fetchMoreData = () => {
...
}
Upvotes: 1