Reputation: 3611
I would like to use the SectionList
in react native.
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
dataSource: [
{
title: 'New List', data: []
},
{
title: 'Old list', data: []
},
]
}
}
render() {
return (
<SectionList
style={styles.SectionContainer}
sections={this.state.dataSource}
renderSectionHeader={this._renderSectionHeader}
renderItem={this._renderItem}
keyExtractor={(item) => item.id}
/>
)
}
}
Each section's data can be fetched by separate url, and they basically have the same json data:
getNewList() {
const url = website + '/api/new-list/';
return fetch(url)
.then((res) => res.json())
.catch((err) => console.log(err))
},
getOldList() {
const url = website + '/api/old-list/';
return fetch(url)
.then((res) => res.json())
.catch((err) => console.log(err))
}
How can fetch and store both the response data for the dataSource
of SectionList
?
Upvotes: 0
Views: 1193
Reputation: 16451
Sounds like you need to fire off multiple promises and wait for all to complete. Axios has an awesome .all
helper utility that lets you pass in an array of promises and then waits for all of them to finish before running resolving:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
You can also do something close to this using native Promises:
getLists(){
this.getListData().then( responses => {
this.setState({
dataSource: [
{
title: 'New List', data: responses[0]
},
{
title: 'Old list', data: responses[1]
},
]
)};
});
}
getListData(){
return new Promise( (resolve, reject) => {
let completes = 0;
let responses = [];
let url = website + '/api/new-list/';
fetch(url)
.then((res) => {
responses.push(res.json());
completes++;
if(completes === 2){
resolve(responses);
}
})
.catch((err) => console.log(err));
url = website + '/api/old-list/';
fetch(url)
.then((res) => {
responses.push(res.json());
completes++;
if(completes === 2){
resolve(responses);
}
})
.catch((err) => console.log(err))
});
}
Upvotes: 1