Search posts, tags, users, and pages
In your onScroll method, use setState to add to the list of properties in the component's state. Like so:
this.setState(prevState => ({
properties: [
...prevState.properties,
...data // Data returned from the fetch operation
]
}));
Hi Ronald Roe, Thanks for your help. But I got an issue while implementing this which is
"TypeError: Invalid attempt to spread non-iterable instance"
code
import React, { Component } from "react";
import "./PropertyList.css";
import furnished from "../../assets/bed.svg";
let data = [];
class PropertyList extends Component {
constructor() {
super();
this.state = {
properties: [],
isLoading: true,
error: null
};
}
componentDidMount() {
fetch("demo8213882.mockable.io/fetchProperties")
.then(response => response.json())
.then(resData => {
this.setState({
properties: resData,
isLoading: false
});
data = resData;
})
// Catch any errors we hit and update the app
.catch(error => this.setState({ error, isLoading: false }));
window.addEventListener('scroll', this.onScroll, false);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onScroll, false);
}
onScroll = () => {
if (
(window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 500)) {
this.setState(prevState => ({
properties: [
...prevState.properties,
...data // Data returned from the fetch operation
]
}));
console.log(data)
}
}
render() {
const { isLoading, properties, error } = this.state;
return (
<React.Fragment>
<div className="row">
{error ? <p>{error.message}</p> : null}
{!isLoading? (
properties.data.map((item, index) => {
let length = item.photos.length;
return (
<div className="col-md-4 nb-card">
<div className="card">
<img
className="card-img-top"
src={
item.photos.length >= 1
? "images.nobroker.in/images" +
item.id +
"/" +
item.photos[0].imagesMap.thumbnail
: "via.placeholder.com/200X150"
}
alt="Card image cap"
/>
<div className="card-body">
<h6 className="card-title">{item.title}</h6>
</div>
<ul className="list-group list-group-flush">
<li className="list-group-item">
<span>
<strong> ₹ {item.rent} Rent</strong>
</span>
</li>
<li className="list-group-item">
<span>
<strong>{item.propertySize} sqft</strong>
</span>
</li>
<li className="list-group-item">
<img className="furnished-icon" src={furnished} />
{item.furnishingDesc} Furnished
</li>
</ul>
</div>
</div>
);
})
) : (
// If there is a delay in data, let's let the user know it's loading
<div className="col-md-8"><p>Loading...</p></div>
)}
</div>
</React.Fragment>
);
}
}
export default PropertyList;
That's because data is undefined. What I wrote was not a full example, but simply how to update the properties. You'll have to fetch the new data and then add it the way I showed you.
Additionally, the API you're drawing from will need to be able to return different items in subsequent requests.
Hey Ronald Roe, I have successfully implemented. Thanks for your help.