I am trying to implement pagination. I am fetching array of 10 items in every fetch request
and saving them in state when onEndReached
of listview will called I am fetching next items and so on.
My problem is when I am fetching next array of items, the items from previous fetch which are saved in state they are vanishing. and as I updating the state only currently fetched items are displaying.
I want that items from previous fetch should not vanishes on next fetch. Can I append the new items to the existing state? If yes how can I do it?
If I am going wrong then how can I achieve this using any component of react native which is I am unaware of?
Here is my code
constructor(props) {
super(props);
this.state = {
next: "",
qwerty: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
return fetch('https://shopconapp.herokuapp.com/api/pagination/')
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
qwerty: ds.cloneWithRows(responseData.results.post),
});
}
})
}
_onEndReached(){
url = this.state.nexturl;
return fetch(this.state.nexturl)
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
qwerty: ds.cloneWithRows(responseData.results.post),
});
}
})
}
<ListView
dataSource={this.state.qwerty}
onEndReachedThreshold={2}
onEndReached={this._onEndReached.bind(this)}
/>
add posts
to your state
this.state = {
next: "",
posts : []
qwerty: []
};
for the fetchData method save the state of posts
fetchData() {
return fetch('https://shopconapp.herokuapp.com/api/pagination/')
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
posts : responseData.results.post ,
qwerty: ds.cloneWithRows(responseData.results.post),
});
}
})
}
now in onEndReach
append the new posts to previous posts and make your data source from the state
_onEndReached(){
url = this.state.nexturl;
return fetch(this.state.nexturl)
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let posts = this.state.posts.concat(responseData.results.post);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
posts : posts ,
qwerty: ds.cloneWithRows(posts),
});
}
})
}