Search code examples
javascriptreactjsreact-nativereact-android

React Native set var from fetch


in my render function I am trying to display the name of a company. Therefore I call a function getCompanyByShortlink where I want to assign a value company_name to this.company. I checked the response and it contains all data I need, so no problems here.

However this doesn't work, the value is not assigned. If I enter return this.company = "test"; directly, it works perfectly fine.

I would really appreciate if someone could help me to set the right value which comes from my API.

Thanks, Oliver

class Company extends React.Component {
   constructor(props){
   super(props);
   this.shortlink = this.props.shortlink;
   this.company = null;
}

getCompanyByShortlink(shortlink){
  //this works perfectly fine!
  // return this.company = "test";
  fetch('http://192.168.178.96:81/api/v1/companies/'+shortlink).then((response) => response.json())
  .then((responseJson) => {
  //this does not work for any reason.
  return this.company = responseJson.data.company.company_name;
})
  .catch((error) => {
    console.warn(error);
  });
}
render() {
  this.company =   this.getCompanyByShortlink(this.shortlink);
  return (
    <View style={styles.mainContainer}>
    <Text style={styles.mainWelcome}>Your Company: {this.company} </Text>
    </View>
    );
}

};


Solution

  • You should't do async ops in the render function. Try it this way:

    class Company extends React.Component {
      constructor(props){
        super(props);
        this.shortlink = this.props.shortlink;
    
        this.state = {
          company: null
        };
    
        this.getCompanyByShortlink(this.shortlink).then((company) => {
          this.setState({company});
        });
      }
    
      getCompanyByShortlink(shortlink){
        //this works perfectly fine!
        // return this.company = "test";
    
        fetch('http://192.168.178.96:81/api/v1/companies/'+shortlink)
          .then((response) => response.json().data.company.company_name)
          .catch((error) => console.warn(error));
      }
    
      render() {
        return (
          <View style={styles.mainContainer}>
          <Text style={styles.mainWelcome}>Your Company: {this.state.company} </Text>
          </View>
          );
      }
    }