Hello I am trying to add infinite scroll with a loop that renders posts. However, I kept getting the following error that my obj is undefined. Does anyone know what went wrong?
ERROR:
Uncaught TypeError: Cannot read property 'next' of undefined
at Object.fetchMoreData [as next] (bundle.js:27529)
at InfiniteScroll.onScrollListener (bundle.js:27932)
at InfiniteScroll.<anonymous> (bundle.js:28093)
fetchMoreData @ bundle.js:27529
onScrollListener @ bundle.js:27932
(anonymous) @ bundle.js:28093
the api is as follows. Here I am keeping track of the api url of the next things I should show on the page if the infinite scroll is triggered.
{
"next": "/api/v1/p/?size=1&page=2",
"results": [
{
"postid": 2,
"url": "/api/v1/p/2/"
}
],
"url": "/api/v1/p/"
}
my code is as follows. I tried both state and props in the fetchMoreData() but neither worked.
constructor(props) {
// Initialize mutable state
super(props);
this.state = { results: [], next: "", url: ""};
}
componentDidMount() {
// Call REST API to get number of likes
fetch(this.props.url, { credentials: 'same-origin' })
.then((response) => {
if (!response.ok) throw Error(response.statusText);
return response.json();
})
.then((data) => {
this.setState({
results: data.results,
next: data.next,
url: data.url,
});
})
.catch(error => console.log(error));
}
fetchMoreData() {
fetch(this.props.next, {method: 'GET'})
.then((response)=>{
return response.json();
})
.then((data)=>{
this.setState({
results: this.state.results.concat(data.results),
next: data.next,
});
});
}
render() {
let has_more;
if( this.state.next == '' ){
has_more = false;
} else {
has_more = true;
}
return (
<InfiniteScroll next={this.fetchMoreData} hasMore={has_more}>
<ul>
{this.state.results.map((post)=> (
<li><Post url={post.url}/></li>
))}
</ul>
</InfiniteScroll>
);
}
Aucun commentaire:
Enregistrer un commentaire