I'm creating a React Native Android App that pulls data from a database and displays it.
I would like to run a Javascript Function before the render() displays the variables.
as
render() {
return (
<View><Text>{ data }</Text></View>
);
}
Doesn't work because the variables aren't defined yet.
You can make use of componentDidMount function to call an api (if you want to call it only once) that returns you the data which you can save in the state and render
class App extends React.Component {
state = {
data: [],
loading: true
}
componentDidMount() {
ApiCall().then((data) => {
this.setState({data, loading: false})
})
}
render() {
if(this.state.loading) {
return 'Loading...'
}
return (
<View><Text>{this.state.data.map((obj => <View>{/* return that you want here from obj*/}</View>))}</Text></View>
);
}
}
To enhance UserExperience, you can have a loading state till your data is ready.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With