infinite scroll not working properly in React - javascript

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?

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

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).

Related

Cannot read properties of undefined (reading 'data') on my React WP RestFul Api

My code was working fine until i added a new blog post and I got this error on my console making my React Application goes blank. after looking around, I was unable to fix the issue.
bellow is my code:
import React from "react";
import { Link, NavLink } from "react-router-dom";
import axios from "axios";
import renderHTML from "react-render-html";
import Loader from "../img/loader.gif";
import { formatDistanceToNow } from 'date-fns';
class Blog extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
posts: [],
error: "",
};
}
componentDidMount() {
const wordPressSiteUrl = "https://my-api-site-address";
this.setState({ loading: true }, () => {
axios
.get(`${wordPressSiteUrl}/wp-json/wp/v2/posts/?per_page=10`)
.then((res) => {
this.setState({ loading: false, posts: res.data });
})
.catch((error) =>
this.setState({ loading: false, error: error.response.data.message })
);
})
}
render() {
const { posts, loading , error } = this.state;
return (
<div>
<main>
<div id="heading">
<h2>Latest News</h2>
</div>
{error && <div className="alert alert-danger">{error}</div>}
{posts.length ? (
<article>
{posts.map((post) => (
<div
key={post.id}
id="blogrow"
className="row"
style={{
backgroundColor: "rgb(50,52,54)",
marginBottom: "10px",
paddingBottom: "10px",
}}
>
<div className="col-4 resize">
<img className="postimg"
src={post.better_featured_image.source_url}
style={{
borderRadius: "10px"
}}
alt="{post.title.rendered}"
/>
</div>
<div className="col-8 blogcol-8">
<h3 id="blogheadercss">
<Link to={`/posts/${post.id}`} dangerouslySetInnerHTML={{ __html: post.title.rendered}} style={{ color: "#FFC107" }}></Link>
</h3>
<p id="blogcontentcss">
{renderHTML(post.excerpt.rendered)}
</p>
<div className="col">
<div className="row mt">
<div className="col-lg-6 col-md-6 col-sm-6">
<button id="datetime" className="btn btn-outline-warning btn-sm">
{ post.x_date }
</button>
</div>
<div className="col-lg-6 col-md-6 col-sm-6">
<div
id="readmore"
className="btn btn-outline-primary btn-sm"
>
<Link to={`/posts/${post.id}`} style={{ color: "white" }}>
Read More
</Link>
</div>
</div>
</div>
</div>
</div>
</div>
))}
</article>
) : (
""
)}
{ loading && <img className="loader" src={Loader} alt="Loading" /> }
</main>
<div
className="container"
style={{
marginTop: "10px",
paddingRight: "50px",
textAlign: "right",
}}
>
<button className="btn btn-outline-primary">
<NavLink exact to="/blogs">
Explore More
</NavLink>
</button>
</div>
</div>
);
}
}
export default Blog;
I will like to fix an error with auto fetch API every 5mins.
i will be glad if someone can work me through.
Thanks
There's a CORS preflight, basically if you make a request, it will send OPTIONS first
That's why the res will be undefined and res.data cannot be read
So make a conditional first wherein it runs only if the res is not undefined
the componentDidMount function should be modified like this
componentDidMount() {
const wordPressSiteUrl = "https://my-api-site-address";
this.setState({ loading: true }, () => {
axios
.get(`${wordPressSiteUrl}/wp-json/wp/v2/posts/?per_page=10`)
.then((res) => {
if(res)
this.setState({ loading: false, posts: res.data });
})
.catch((error) =>
this.setState({ loading: false, error: error.response.data.message })
);
})
}

React is only passing the last object in my array to a component

I have a react component where I map through a list of clients and display each client in a card.
return (
<div className='VolunteerClientsTab'>
{volunteerClients && volunteerClients.map((client) => (
<React.Fragment key={client.id}>
<div className='VolunteerClientsTab__card'>
<Avatar style={{ alignSelf: 'center', marginTop: '.5rem' }}>{client.first_name[0]}{client.last_name[0]}</Avatar>
<h2>{client.first_name} {client.last_name}</h2>
<h4>Details</h4>
<p><AiOutlineMail style={iconStyles} /> {client.email}</p>
<p><AiOutlinePhone style={iconStyles} /> {formatPhoneNumber(client.contact_number)}</p>
<h4 style={{ marginTop: '1rem' }}>Actions</h4>
<p onClick={handleOpenClientNeedsModal} className='hover-underline'><BiDonateHeart style={iconStyles} />View Needs</p>
<p className='hover-underline'><HiOutlineDocumentReport style={iconStyles} />Write Report</p>
<p className='hover-underline'><FiVideo style={iconStyles} />Contact Client</p>
</div>
<ClientNeeds open={openClientNeedsModal} handleClose={handleCloseClientNeedsModal} client={client} />
</React.Fragment>
))}
</div>
)
};
ClientNeeds is a component that renders an MUI modal to display additional client information. I am passing it the client object within the loop but when I open the modal only the client of the last index in the volunteerClients array was passed to all the modal components. Does anyone have any idea why this is happening?
ClientNeeds component
import React from 'react';
import Box from '#mui/material/Box';
import Modal from '#mui/material/Modal';
import PropTypes from 'prop-types';
const style = {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
bgcolor: 'background.paper',
border: '2px solid #000',
boxShadow: 24,
p: 4,
};
const ClientNeeds = ({ open, handleClose, client }) => {
return (
<div>
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<h2>{client.email}</h2>
</Box>
</Modal>
</div>
)
};
ClientNeeds.propTypes = {
open: PropTypes.bool,
handleClose: PropTypes.func,
client: PropTypes.object
};
export default ClientNeeds;
MY SOLUTION
Passing the client onClick to an additional global state object and passing that state object to the modal,
const [selectedClient, setSelectedClient] = useState(null)
also only rendering the clientNeedsModal is there is an object in that state.
<div className='VolunteerClientsTab'>
{volunteerClients && volunteerClients.map((client) => (
<React.Fragment key={client.id}>
<div className='VolunteerClientsTab__card'>
<Avatar style={{ alignSelf: 'center', marginTop: '.5rem' }}>{client.first_name[0]}{client.last_name[0]}</Avatar>
<h2>{client.first_name} {client.last_name}</h2>
<h4>Details</h4>
<p><AiOutlineMail style={iconStyles} /> {client.email}</p>
<p><AiOutlinePhone style={iconStyles} /> {formatPhoneNumber(client.contact_number)}</p>
<h4 style={{ marginTop: '1rem' }}>Actions</h4>
<p onClick={() => handleOpenNeeds(client)} className='hover-underline'><BiDonateHeart style={iconStyles} />View Needs</p>
<p className='hover-underline'><HiOutlineDocumentReport style={iconStyles} />Write Report</p>
<p className='hover-underline'><FiVideo style={iconStyles} />Schedule Meeting</p>
</div>
{selectedClient ? (
<ClientNeeds open={openClientNeedsModal} handleClose={handleCloseClientNeedsModal} client={selectedClient} />
) : null}
</React.Fragment>
))}
</div>
const handleCloseClientNeedsModal = () => {
setSelectedClient(null)
setOpenClientNeedsModal(false);
}
const handleOpenNeeds = (client) => {
setSelectedClient(client)
handleOpenClientNeedsModal()
}
This allows me to pass any individual object within my array to the modal component as originally desired

Image not displaying in React

I'm having an issue getting an image to appear within my React project. I've done it before and actually copied the same exact code to put it into my project, but for some reason nothing is showing up. I looked in the console and inspected the image and it's showing that there is something there, but just not rendering somehow. Nothing I search for online has a similar issue so I'm wondering if I'm just missing something, and that's what causing it not to render.
Here is the parts of my file that pertains to my question.
import React from 'react';
import { Link } from 'react-router-dom';
import Button from '../../components/Spinner/Button';
import ATABanner from '../../../public/Images/ATAbanner-flip.png';
import ATADouble from '../../../public/Images/ATAdouble-1.png';
import ATASingle from '../../../public/Images/ATAsingle-1.png';
import '../../StyleSheets/AdContract.css';
import '../../StyleSheets/Button.css';
export default class CustomerPage extends React.Component{
constructor(props){
super(props);
this.state = {
QuoteID: this.props.match.params.id,
CustomerFirst: "",
CustomerLast: "",
CurrStep: 1,
StoreList: [],
StoresSelected: [],
AdSize: "",
AdSelected: "",
}
}
... extra stuff and methods here
AdSizeHandler(e){
console.log(e.target.id);
switch(e.target.id){
case "SINGLE": this.setState({AdSize: e.target.id});
break;
case "DOUBLE": this.setState({AdSize: e.target.id});
break;
case "BANNER": this.setState({AdSize: e.target.id});
break;
}
}
RenderAdSelected(){
let img = null;
let ad = this.state.AdSize;
if(ad == "SINGLE"){
img = (
<img id="ad-image-single" name='ADSingle' src={ATASingle} alt="" width="100%" scrolling="no"/>
)
}else if(ad == "DOUBLE"){
img = (
<img id="ad-image-double" name='ADDouble' src={ATADouble} alt="" width="100%" scrolling="no"/>
)
}else if(ad == "BANNER"){
img = (
<img id="ad-image-banner" name='ADBanner' src={ATABanner} alt="" width="100%" scrolling="no"/>
)
}
return img;
}
render(){
return(
<div id="CustomerContainer" style={{width: '100%', height: '100%'}}>
<div id="CustomerContent" className="fade-in" style={{textAlign: 'center', width: '100%', height: '100%', overflowY: 'auto'}}>
<div id="Welcome" style={{marginTop: '5%'}}>
<p style={{fontSize: '35px', fontWeight: 'bold'}}>Hello, {this.state.CustomerFirst + " " + this.state.CustomerLast}</p>
<p style={{fontSize: '20px', color: 'orange'}}><b>Your Quote Is Almost Ready!</b></p>
</div>
<div style={{marginTop: '5%', color: '#0F9D58', fontSize: '37px'}}>
<p><b>Step: {this.state.CurrStep}</b></p>
</div>
<div id="InnerContainer" style={{width: '80%', marginLeft: 'auto', marginRight: 'auto'}}>
{this.RenderStoreSelect(this.state.CurrStep)}
<div id="ad-select">
<div className="fade-in" id="ad-prompt">
<p style={{fontSize: '20px'}}><b>Please Select Your Ad Size</b></p>
</div>
<div id="ad-buttons" style={{display: 'inline-block', marginTop: '2%'}}>
<span style={{display: 'flex'}}>
<Button name="SINGLE" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
<Button name="DOUBLE" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
<Button name="BANNER" color="G-green" click={this.AdSizeHandler.bind(this)}></Button>
</span>
</div>
<div>
<img id="adImage" name='ADSingle' src={ATASingle} alt="" width="100" height="100"/>
</div>
</div>
</div>
{this.ConfirmQuote()}
</div>
</div>
)
}
}
Here is proof that it's retrieving the image:
If anyone has any idea what I'm possibly doing wrong, please let me know. Thanks.
I found out the reason for this issue. The problem is that I am in a different route than the home route '/'. I solved my problem by doing this instead: <img id="adImage" name='ADSingle' src={`/${ATASingle}`} alt="" width="100" height="100"/>

Unable to set zIndex fro autocomplete in reactjs

I am working on a project where i have to implement a search bar which should be in my header component , when ever i try to search the search is working fine but at the same time the search options are overlapping the my content below it. how can i resolve this?
I tried adding zIndex both using css and noraml jsx way both dint work for me bellow is my code.
Header.js
import React, { Component } from 'react';
import Autocomplete from 'react-autocomplete';
import { getStocks, matchStocks } from './data';
class Header extends Component {
state = { value: '' };
render() {
return (
<div style={{ marginTop: 0, marginLeft: 0 }}>
<div className="callout primary" id="Header">
<div className="row column">
<h1>{this.props.name}</h1>
<div style={{ zIndex: 10 }}> // this is where i am trying to set the zIndex
<Autocomplete
classNames={{ autocompleteContainer: 'ac-container' }}
value={ this.state.value }
inputProps={{ id: 'states-autocomplete' }}
wrapperStyle={{ position: 'relative', display: 'inline-block' }}
items={ getStocks() }
getItemValue={ item => item.name }
shouldItemRender={ matchStocks }
onChange={(event, value) => this.setState({ value }) }
onSelect={ value => this.setState({ value }) }
renderMenu={ children => (
<div className = "menu">
{ children }
</div>
)}
renderItem={ (item, isHighlighted) => (
<div
className={`item ${isHighlighted ? 'item-highlighted' : ''}`}
key={ item.abbr } >
{ item.name }
</div>
)}
/>
</div>
</div>
</div>
</div>
);
}
}
export default Header;

Uncaught (in promise) TypeError: Cannot read property 'companies' of undefined

I would like to have a list of items with infinite scroll and I am using this package https://github.com/CassetteRocks/react-infinite-scroller but in the documentation there is nothing mentioned how the fetching function looks like.
In my code I have it like this:
this.state = {
companies: [],
page: 0,
resetResult: false,
};
fetchCompanies(page){
traineeship.getAll(page).then(response => {
if (response.data) {
this.setState({ companies: this.state.companies.concat(response.data._embedded.companies) });
} else {
console.log(response);
}
});
}
componentDidMount() {
this.fetchCompanies(this.state.page);
}
<InfiniteScroll
pageStart={0}
loadMore={this.fetchCompanies}
hasMore={true || false}
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 style={{
fontSize: '18px',
lineHeight: '18px'
}}>{traineeship.name}</p>
</div>
{
traineeship.video === 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: '18px',
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"}>
<a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
<p className={"primaryColor"}
style={{ fontSize: '13px' }}>{traineeship.city}(show in
map)</p>
</a>
</div>
</div>
<div className={"companyDescription"}>
<p className={"secondaryColor"} style={{
fontSize: '14px',
lineHeight: '20px'
}}>{traineeship.description}</p>
</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>
Full message error:
Uncaught (in promise) TypeError: Cannot read property 'companies' of
undefined
at eval (traineeships.component.js:71)
Edit: (I no longer have the error but loadmore seems not trigger at all)
import React from 'react';
import {Route, Link} from 'react-router-dom';
import FourthView from '../fourthview/fourthview.component';
import {Bootstrap, Grid, Row, Col, Button, Image, Modal, Popover} from 'react-bootstrap';
import traineeship from './traineeship.api';
import Header from '../header/header.component';
import InfiniteScroll from 'react-infinite-scroller';
require('./traineeship.style.scss');
class Traineeship extends React.Component {
constructor(props) {
super(props);
this.state = {
companies: [],
page: 0,
resetResult: false,
};
}
componentDidMount() {
this.fetchCompanies(this.state.page);
}
fetchCompanies(page){
traineeship.getAll(page).then(response => {
if (response.data) {
this.setState({companies: this.state.companies.concat(response.data._embedded.companies)});
} else {
console.log(response);
}
});
}
render() {
return (
<div className={"wrapperDiv"}>
{JSON.stringify(this.props.rootState)}
<div className={"flexDivCol"}>
<div id="header">
<Header/>
</div>
<div id="result">
<div className={"search"}>
<h2>Harjoittelupaikkoja</h2>
<p className={"secondaryColor"}>{this.state.companies.length} paikkaa löydetty</p>
</div>
<div className={"filters"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
Hakukriteerit</h5>
<div className={"filter"}>Ravintola- ja cateringala</div>
<div className={"filter"}>Tarjoilija</div>
<div className={"filter"}>Kaikki</div>
</div>
<div className={"searchResults"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
Hakutulokset</h5>
<InfiniteScroll
pageStart={0}
loadMore={() => this.fetchCompanies.bind(this)}
hasMore={true || false}
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 style={{
fontSize: '18px',
lineHeight: '18px'
}}>{traineeship.name}</p>
</div>
{
traineeship.video === 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: '18px',
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"}>
<a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
<p className={"primaryColor"}
style={{fontSize: '13px'}}>{traineeship.city}(show in
map)</p>
</a>
</div>
</div>
<div className={"companyDescription"}>
<p className={"secondaryColor"} style={{
fontSize: '14px',
lineHeight: '20px'
}}>{traineeship.description}</p>
</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 Traineeship;
So basically it just shows only first five article, page is not increasing!
#Mizlul: Does fetchCompanies invoked every time scroll happens ? Can you please check that ? Also you are mutating the state here, this.state.companies.concat(response.data._embedded.companies)..
Can you update it to ,
const companies = Array.from(this.state.companies);
this.setState({ companies: companies.concat(response.data._embedded.companies) });
I'm not sure about that .bind(this). Try making your method an arrow function (to implicitly bind the this context):
constructor() {
// ...
this.fetchCompanies = this.fetchCompanies.bind(this);
}
fetchCompanies(page) {
return traineeship.getAll(page).then(response => {
if (response.data) {
this.setState({
companies: this.state.companies.concat(
response.data._embedded.companies
)
});
} else {
console.log(response);
}
});
}
// In your render's return:
<InfiniteScroll
pageStart={0}
loadMore={() => this.fetchCompanies(this.state.page)}
hasMore={true || false}
loader={
<div className="loader" key={0}>
Loading ...
</div>
}
useWindow={false}
>;

Categories