I am getting the following warning message when my AsyncStorage Item is empty “Possible Unhandled Promise Rejection (id:0)” So my question is: How can I handle a promise rejection?
My code:
JavaScript
x
27
27
1
componentDidMount() {
2
try {
3
// This warning only appears when 'connections' item is empty
4
AsyncStorage.getItem('connections').then((token) => {
5
token = JSON.parse(token);
6
7
const getSectionData = (dataBlob, sectionId) => dataBlob[sectionId];
8
const getRowData = (dataBlob, sectionId, rowId) => dataBlob[`${rowId}`];
9
10
const ds = new ListView.DataSource({
11
rowHasChanged: (r1, r2) => r1 !== r2,
12
sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
13
getSectionData,
14
getRowData,
15
});
16
17
const {dataBlob, sectionIds, rowIds} = this.formatData(token);
18
19
this.setState({
20
dataSource: ds.cloneWithRowsAndSections(dataBlob, sectionIds, rowIds),
21
});
22
});
23
}catch(error) {
24
console.log(error);
25
}
26
}
27
Advertisement
Answer
You need to catch the reject of the promise:
JavaScript
1
25
25
1
componentDidMount() {
2
// This warning only appears when 'connections' item is empty
3
return AsyncStorage.getItem('connections').then((token) => {
4
token = JSON.parse(token);
5
6
const getSectionData = (dataBlob, sectionId) => dataBlob[sectionId];
7
const getRowData = (dataBlob, sectionId, rowId) => dataBlob[`${rowId}`];
8
9
const ds = new ListView.DataSource({
10
rowHasChanged: (r1, r2) => r1 !== r2,
11
sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
12
getSectionData,
13
getRowData,
14
});
15
16
const { dataBlob, sectionIds, rowIds } = this.formatData(token);
17
18
this.setState({
19
dataSource: ds.cloneWithRowsAndSections(dataBlob, sectionIds, rowIds),
20
});
21
}).catch(error => {
22
console.log(error);
23
})
24
}
25