Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data unavailable before render method is executed - React Native

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.

like image 964
Teobot Avatar asked Mar 28 '26 17:03

Teobot


1 Answers

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.

like image 157
Shubham Khatri Avatar answered Mar 31 '26 05:03

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!