Reputation: 1060
I have a component that fetches data from an api, then will display the data on the screen. What I would like to know, is how do I delay displaying the text on the screen until the api call is complete?
Ex:
Your Balance is ____
after network call resolves
Your Balance is 500
but "Your Balance is"
displays as soon as the component is rendered.
import React, { Component, PropTypes } from 'react'
import {StyleSheet, View, Text} from 'react-native'
export default class Main extends Component {
constructor(props) {
super(props);
this.state = {
accountBalance: ''
};
fetch('someURL', {method: "GET"})
.then((response) => response.json())
.then((responseData) => {
this.setState({
accountBalance: responseData.amount
})
})
.done();
}
render() {
return (
<View style={styles.container}>
<Text style={{color: '#FFF'}}> Your Account Balance is {this.state.accountBalance} </Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
paddingTop: 74,
backgroundColor: 'black'
}
})
Upvotes: 0
Views: 1911
Reputation: 366
In this case, you could do something as simple as returning null
when there is no balance:
render() {
return (
<View style={styles.container}>
{this.state.accountBalance ? (
<Text style={{color: '#FFF'}}> Your Account Balance is {this.state.accountBalance} </Text>
) : null}
</View>
)
}
You could track the request using a separate state variable as well, such as this.state.balanceLoaded: false
and return null
until that changes. You then would update that value to true
in your fetch
callback. This would solve issues where the value was returned but falsy, such as ''
or 0
Upvotes: 1