0

I am having problems trying to run a function when the page is at the very bottom. I am trying to grab more data from my database when the page is at the very bottom.

My code structure looks something like this

constructor(){
        super();
        this.state = {
            render_count: 1,
        }
        this.getFeed.bind(this);
    }

componentDidMount(){
        this.getFeed();
        window.addEventListener('scroll', function() {
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
                console.log("you're at the bottom of the page");
                this.setState({render_count: this.state.render_count+1});
                this.getFeed();
            }
        });
    }

getFeed(){//get node.js data}

It seems like this.state is null or some reason. Im getting an error "Cannot read property 'render_count' of undefined" Its also not reading this.getFeed either().

Thanks for all the help!

2 Answers2

0

You are in a new scope when in window.addEventListener('scroll', function() {}. the keyword this does not refer anymore to the React class in question, but the eventListner.

This can be fixed with either using an arrow function

window.addEventListener('scroll', () => {})

Or saving this to a variable or constant

componentDidMount(){
        this.getFeed();
        const self = this;
        window.addEventListener('scroll', function() {
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
                console.log("you're at the bottom of the page");
                self.setState({render_count: self.state.render_count+1});
                self.getFeed();
            }
        });
    }
ErikM
  • 154
  • 2
-2

function() {} functions do not capture this, which you'll need.

Use an arrow function instead: () => { ... }.

See https://stackoverflow.com/a/34361380/51685 for more details.

Ps. Remember to remove that event listener at some point too.

AKX
  • 152,115
  • 15
  • 115
  • 172