Search code examples
reactjsinfinite-scroll

React infinity scroll reset state after click back in browser


I started using React a few days ago. Now I already had some experience with jQuery but this works much better!

I added an infinity scroll and this all works great, but there is one thing that doesn't work well ...

I have a list of items (community) with a link in it. This link goes to a page associated with the post. (for example: community / 2020202233)

When I am there and want to go back to the community page, everything starts again at the beginning.

Obviously, since I access the componentDidMount and everything is reloaded again.

How can I prevent this from happening. I tried bringing it to a parent but the page loads with

This is my code:

state = {
    posts: [],
    limit: 10,
    start: 0, 
    maxPosts: 0
};


 componentDidMount(){

    const countPosts = config.conversations.databaseUrl + "?action=count_posts";
     axios.get(countPosts).then(count => {
        this.setState({ maxPosts: count.data });
    });

    const allPosts = config.conversations.databaseUrl + '?action=all_posts&start=' + this.state.start + '&limit=' + this.state.limit;
     axios.get(allPosts).then(posts => {
         //console.log(posts)
        this.setState({
            posts: posts.data,
            start: this.state.start + this.state.limit
        });
    });
        
    window.addEventListener('scroll', this.loadMore);
}


componentWillUnmount(){
    window.removeEventListener('scroll', this.loadMore);
}
  
loadMore = () => {
    if (window.innerHeight + document.documentElement.scrollTop + 1 >= document.scrollingElement.scrollHeight) {

        if (this.state.maxPosts > this.state.start) {

            const messages = config.conversations.databaseUrl + '?action=all_posts&start=' + this.state.start + '&limit=' + this.state.limit;
            axios.get(messages).then(posts => {
                
                const post = [...this.state.posts, ...posts.data];

                this.setState({
                    posts: post,
                    start: this.state.start + this.state.limit
                });
            });
        }
    }
}

render() {
    return (
        <main>
            <div className="my-3 p-3 bg-body rounded">
                <h6 className="border-bottom pb-2 mb-0">Suggestions</h6>
                <ul>
                    {this.state.posts.map(items => (
                        <Link key={items.post_id} to={`/community/${items.post_name}`}>
                            <Conversation items={items} />
                        </Link>
                    ))}
                
                </ul>
                <small className="d-block text-end mt-3">
                <a href="#">All suggestions</a>
                </small>
            </div>
        </main>
    );
};

Solution

  • you should look into redux state management or use the contextAPI from react (will require changing the class components to functional ones)