the code I have put down below will call fetch() to recieve some data and only after fetching it will display one output. But this always fails to update the view after the async call. I'm new to this react native async calls so I'd like to have some help on this. Here is the necessary parts of the code.
import React from 'react'import {StyleSheet, View, ScrollView, Alert} from 'react-native';import {Card, Button, Text} from 'react-native-elements';import {TextField} from 'react-native-material-textfield';class MyScreen extends React.Component { static navigationOptions = ({navigation}) => ({ title: 'Title' }); constructor(props) { super(props); const {navigation} = this.props; this.state = { loaded: false }; } async componentWillMount() { let responseJson = await this.fetchData().done(); console.log(responseJson); console.log('componentWillMount finished'); } fetchData = async () => { const response = await fetch('myurl/'+ GLOBAL.account_data.account.emp_number, { method: 'GET', headers: new Headers({'Authorization': 'Bearer '+ GLOBAL.access_token,'Content-Type': 'application/json' }) }); return await response.json(); }; render() { let view; console.log('in render'); if (this.state.loaded) { view = <Text>Vikasitha</Text> } else { view = <Text>Buddhi</Text> } return ( view ) }}const styles = StyleSheet.create({ card_info: { flex: 1, height: 10 }, card_leave: { flex: 2, height: 30 }});export default MyInfoPersonalDetailsScreen;
The console log are printed in the following order.
console.log('in render')console.log(responseJson) //prints undefinedconsole.log('componentWillMount finished')
But if the await and async functions synchronize correctly, this should be in the order,
console.log(responseJson)console.log('componentWillMount finished')console.log('in render')
- Is it? (this is from my understanding.)
- Correct usage of componentWillMount? (used componentWillMount because this should execute before rendering. Not like componentDidMount)
I just want to get the flow in the correct order. It is about the order of execution when constructor, componentWillMount and render is used. Don't worry about the unused variables and missing parts.
Any help appreciated!!