Main constructor
constructor(props) {
super(props);
this.state = {
page: 1,
articles: [],
loading: false,
isActive: false,
};
}
Using componentDidMount method
async componentDidMount() {
const url = `https://newsapi.org/v2/top-headlines?country=us&category=${this.props.category}&apiKey=ff954e750b914328a0bc65c2e45304c4&page=1&pageSize=${this.props.pageSize}`;
this.setState({ loading: true });
let data = await fetch(url);
let parsedData = await data.json(data);
this.setState({
articles: parsedData.articles,
totalArticlesResults: parsedData.totalResults,
loading: false,
});
}
Trying to debug in the console "testing", but this function (loadFunc) isn't trigger inside the
loadFunc = async () => {
console.log('testing');
const url = `https://newsapi.org/v2/top-headlines?country=us&category=${this.props.category}&apiKey=ff954e750b914328a0bc65c2e45304c4&page=${this.state.page + 1}&pageSize=${this.props.pageSize}`;
this.setState({ loading: true });
let data = await fetch(url);
let parsedData = await data.json(data);
this.setState({
articles: [...this.state.articles, ...this.parsedData.articles],
totalArticlesResults: parsedData.totalResults,
loading: false
})
}
Rendering jsx and mapping through the elements from API
render() {
return (
<div className="container my-3">
{/* Infinite scrolling */}
<InfiniteScroll
dataLength={this.state.articles.length}
next={this.loadFunc}
hasMore={this.state.articles.length !== this.state.totalArticlesResults}
loader={<Spinner />}
>
container inside InfiniteScroll Component
<div className="container">
<div className="row">
{!this.state.loading &&
this.state.articles.map((element, index) => {
returning in mapping
return (
<div className="col-md-4" key={index}>
..
</div>
);
})}
</div>
</div>
</InfiniteScroll>
</div>
);
}
Based on documentation
children is by default assumed to be of type array and its length is used to determine if loader needs to be shown or not, if your children is not an array, specify this prop to tell if your items are 0 or more.
In your case you have only one child <div className="container" />.
The solution could be to change the render method to render an array of children. And I think the condition !this.state.loading is bad because it will blink and if the library rely on children as array, it can break the functionality.