1

I am using infinite scroll plugin for react.js and for some reason it is not working the way it is supposed to work.

The problem is that all the requests are made at once when the page loads, and not like for example a request should be made for each time I scroll.

My code looks like below:

import React from 'react';
import {Route, Link} from 'react-router-dom';
import FourthView from '../fourthview/fourthview.component';
import {withRouter} from 'react-router';
import {Bootstrap, Grid, Row, Col, Button, Image, Modal, Popover} from 'react-bootstrap';
import traineeship from './company.api';
import Header from '../header/header.component';
import InfiniteScroll from 'react-infinite-scroller';

require('./company.style.scss');

class Traineeship extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            companies: [],
            page: 0,
            resetResult: false,
            hasMore: true,
            totalPages: null,
            totalElements: 0,
        };
    }

    componentDidMount() {
        this.fetchCompanies(this.state.page);
    }

    fetchCompanies = page => {
        let courseIds = '';

        this.props.rootState.filterByCourseIds.map(function (course) {
            courseIds = courseIds + '' + course.id + ',';
        });

        traineeship.getAll(page, this.props.rootState.selectedJob, courseIds.substring(0, courseIds.length - 1), this.props.rootState.selectedCity).then(response => {
            if (response.data) {
                const companies = Array.from(this.state.companies);
                if(response.data._embedded !== undefined){
                    this.setState({
                        companies: companies.concat(response.data._embedded.companies),
                        totalPages: response.data.page.totalPages,
                        totalElements: response.data.page.totalElements,
                    });
                }

                if (page >= this.state.totalPages) {
                    this.setState({hasMore: false});
                }
            } else {
                console.log(response);
            }
        });
    };

    render() {
        return (
            <div className={"wrapperDiv"}>
                {/*{JSON.stringify(this.props.rootState)}*/}
                <div className={"flexDivCol"}>
                    <div id="header2">
                        <div style={{flex: .05}}>
                            <img src="assets/img/icArrowBack.png" onClick={() => this.props.history.go(-1)}/>
                        </div>
                        <div style={{flex: 3}}>
                            <Header size="small"/>
                        </div>
                    </div>
                    <div id="result">
                        <div className={"search"}>
                            <h2 style={{fontSize: 22}}>Harjoittelupaikkoja</h2>
                            <p className={"secondaryColor LatoBold"} style={{fontSize: 13}}>{this.state.totalElements} paikkaa löydetty</p>
                        </div>
                        <div className={"filters"}>
                            <h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
                                <strong>Hakukriteerit</strong></h5>
                            {
                                this.props.rootState.filters.map((filter, key) => (
                                    <div key={key} className={"filter"}>{filter.title}</div>
                                ))
                            }
                        </div>
                        <div className={"searchResults"}>
                            <h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
                                <strong>Hakutulokset</strong></h5>
                            <InfiniteScroll
                                pageStart={0}
                                loadMore={this.fetchCompanies}
                                hasMore={this.state.hasMore}
                                loader={<div className="loader" key={0}>Loading ...</div>}
                                useWindow={false}
                            >
                                {
                                    this.state.companies.map((traineeship, key) => (
                                        <div id={"item"} key={key}>
                                            <div className={"companyInfo"}>
                                                <div className={"heading"}>
                                                    <div id={"companyDiv"}>
                                                        <p className={"LatoBlack"} style={{
                                                            fontSize: '18px',
                                                            lineHeight: '23px'
                                                        }}>{traineeship.name}</p>
                                                    </div>
                                                    {
                                                        traineeship.mediaUrl == null
                                                            ? ''
                                                            :
                                                            <div id={"videoDiv"}>
                                                                <div className={"youtubeBox center"}>
                                                                    <div id={"youtubeIcon"}>
                                                                        <a className={"primaryColor"}
                                                                           href={traineeship.mediaUrl}>
                                                                        <span style={{marginRight: '3px'}}><Image
                                                                            src="http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c545.png"
                                                                            style={{
                                                                                width: '24px',
                                                                                height: '17px'
                                                                            }}/></span>
                                                                            <span> <p style={{
                                                                                fontSize: '13px',
                                                                                lineHeight: '24px',
                                                                                margin: 0,
                                                                                display: 'inline-block'
                                                                            }}>Esittely</p></span>
                                                                        </a>
                                                                    </div>
                                                                    <div id={"txtVideo"}>

                                                                    </div>
                                                                </div>
                                                            </div>
                                                    }

                                                </div>
                                                <div className={"location"}>
                                                    <div id={"locationIcon"}>
                                                        <Image src="assets/img/icLocation.png"
                                                               style={{marginTop: '-7px'}}/>
                                                    </div>
                                                    <div id={"address"}>
                                                        {
                                                            traineeship.addresses.map((address, key) => {
                                                                return (
                                                                    <a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
                                                                        <p key={key} className={"primaryColor"} style={{fontSize: '13px'}}>{address.street}, {address.city}</p>
                                                                    </a>
                                                                )
                                                            })
                                                        }
                                                    </div>
                                                </div>
                                                <div className={"companyDescription"}>
                                                    <p className={"secondaryColor"} style={{
                                                        fontSize: '14px',
                                                        lineHeight: '20px'
                                                    }}>{traineeship.description}</p>
                                                </div>

                                                <div>
                                                    {

                                                        traineeship.images.map((image, key) => {
                                                            return (
                                                                <img id={"thumbnail"} width={"100%"}
                                                                     src={image.url}
                                                                     style={{
                                                                         width: '80px',
                                                                         height: '80px',
                                                                         marginRight: '10px',
                                                                         marginBottom: '10px'
                                                                     }}
                                                                     alt=""
                                                                     key={key}
                                                                />
                                                            )
                                                        })
                                                    }
                                                </div>

                                                <div className={"companyContacts"} style={{marginTop: '20px'}}>
                                                    <p className={"contactInfo"}>URL: {traineeship.website}</p>
                                                    <p className={"contactInfo"}>Email: {traineeship.email}</p>
                                                    <p className={"contactInfo"}>Puh: {traineeship.phonenumber}</p>
                                                    <p className={"contactInfo"}>Contact: {traineeship.contact}</p>
                                                </div>
                                            </div>
                                        </div>
                                    ))
                                }
                            </InfiniteScroll>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default withRouter(Traineeship);

What can I do so I can eliminate all the request are made when the page is load, I mean this is even worse sending let say 20 request one after another within a second or so.

Any suggestion what is wrong with my code?

Mizlul
  • 1,802
  • 2
  • 27
  • 81

2 Answers2

3

by removing useWindow={false} it is working now!

Mizlul
  • 1,802
  • 2
  • 27
  • 81
  • interesting, so the scroll listener on the parent node causes issues. good that you found it. _useWindow Boolean true Add scroll listeners to the window, or else, the component's parentNode._ – Mario Jun 12 '18 at 12:20
0

Update: Haven't seen that you are using react-infinite-scroller. If you want to build the loader yourself, see my previous answer. With the plugin you can set a threshold.

The answer lies in here: Question: Infinite Scrolling

What you basically need to do is to set a variable in state, isLoading: false, and change it when data comes in via fetch, when data loading done set it back to false. In your infinite scroll function check (this.state.isLoading).

Mario
  • 609
  • 5
  • 16
  • isnt it hasMore that I have defined on my state same as isLoading? – Mizlul Jun 12 '18 at 11:11
  • could u give some example? – Mizlul Jun 12 '18 at 11:11
  • where do i use isLoading within the InfiniteScroll component? – Mizlul Jun 12 '18 at 11:12
  • I added isLoading according as you said, it made it even worse, more requests causing! – Mizlul Jun 12 '18 at 11:15
  • Please setState isLoading: false in traineeship.getALL and in the infinitescroll component where you check scrolling make a condition like this if(this.state.isLoading) { return; } else { this.setState({ isLoading: true }) console.log("page end reached") this.fetchCompanies(); } and the initialstate of isloading is false – Mario Jun 12 '18 at 11:22
  • can u provide a sample of this? – Mizlul Jun 12 '18 at 11:29
  • see updated answer, you can set a threshold before loading more. – Mario Jun 12 '18 at 11:31
  • i have tried threeshold added as well with different values like 250, 500, 1000... nothing seems to work, I actually dont know what value I should assign it with in my case – Mizlul Jun 12 '18 at 11:32