How i can limit the items in the FlatList and add load more?
You Can add the slice(start,end) method while fetching jsondata in datasource. This trick may solve your problem.
dataPosts: responseJson.slice(0,10) replace this line with yours.
If your requirement is to append the existing list from already pulled data in a chunk of 12, then you may consider following strategy which uses onEndReached
and onEndThreshold
to handle the scroll and add 12 records at a time.
Set current page
number to 0
in constructor
constructor(props){
super(props);
this.state = {
... ,
page: 0,
posts: []
}
}
Inside componentDidMount
you need to pull all data from the server and store it in the local state (which you are currently doing), then call the function which will read first 12 records.
componentDidMount() {
return fetch(ConfigApp.URL+'json/data_posts.php')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
page: 0,
dataPosts: responseJson
}, function() {
// call the function to pull initial 12 records
this.addRecords(0);
});
})
.catch((error) => {
});
}
Now add the function which will add records from this.state.dataPosts
addRecords = (page) => {
// assuming this.state.dataPosts hold all the records
const newRecords = []
for(var i = page * 12, il = i + 12; i < il && i <
this.state.dataPosts.length; i++){
newRecords.push(this.state.dataPosts[i]);
}
this.setState({
posts: [...this.state.posts, ...newRecords]
});
}
Now add the scroll handler
onScrollHandler = () => {
this.setState({
page: this.state.page + 1
}, () => {
this.addRecords(this.state.page);
});
}
Render function
render() {
return(
...
<FlatList
...
data={this.state.posts}
renderItem={({item}) => ... }
keyExtractor={(item, index) => index}
onEndReached={this.onScrollHandler}
onEndThreshold={0}
/>
...
);
}
Hope this will help!