I am using Expo of React Native which i need to save the API Fetch response to state.
My code is like this:
onPress={async () => {
if (this.camera) {
const options = { quality:0, base64: true};
let photo = await this.camera.takePictureAsync(options);
setTimeout(()=>{
fetch('https://c7pl8gkrj6.execute-api.ap-southeast-1.amazonaws.com/prod/rekog', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
base64: photo['base64'],
}),
}).then((responseJson) => {
this.setState({
response:responseJson
})
})
.catch((error) => {
console.error(error);
});
this.setState({captured:true})
}, 3000)
}
}}
I want to store the response in the state variable named 'response'. But When I want to display the response saved in state, it will render null.
if(this.state.captured){
console.log(this.state.response)
return(
<View style={styles.container}>
<SectionList
sections={[
{title: 'response1', data: [this.state.response]}
]}
renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
keyExtractor={(item, index) => index}
/>
</View>
);
}else{
...
Here, console.log(this.state.response) shows {} i.e null value. Is it the problem of async function which is not displaying the value saved in state.