0

I am new to React and React-Native and following the docs of React native on the official website. I am making a get call to my API endpoint using fetch. The returned JSON is being shown on the console in Developer's tool but it is not rendering in the Application. I can see all the console logs but not on the Application.

Moreover, if I make my FetchExample Component as default class, then the UI is rendering fine. Where is the problem? Please Help.

class FetchExample extends Component {
  constructor(props){
    super(props);
    this.state ={ isLoading:true}
  }
  componentDidMount(){
      console.log(" mounting")
      return fetch('https://evening-escarpment-86286.herokuapp.com/todo')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          isLoading: false,
          dataSource: responseJson,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }
  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }
    console.log(this.state.dataSource);
    console.log("hi")
    return(
      <View style={{flex: 1, paddingTop:20}}>

        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.id}, {item.name}, {item.message}, {item.time}</Text>}
          keyExtractor={(item, index) => index.toString()}
        />
      </View>
    );
  }
}

export default class LotsOfGreetings extends Component{
  render(){
    return (
      <View style={{alignItems: 'center',  marginTop: 30}}>
        <FetchExample />
      </View>
    );
  }
}
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => LotsOfGreetings);
Abhishek Sah
  • 88
  • 2
  • 8

2 Answers2

0

Can you try by initialize a dataSource to see if it works?

constructor(props){
    super(props);
    this.state = { isLoading:true, datasource: []}
}
GauthierG
  • 308
  • 1
  • 7
0

Well, this thing was solved by putting the API call(fetch) in the constructor itself and not in componentDidMount method. Although I don't think it's a good way as for React-Native documentation says we should make API calls in the componentDidMount method.

Abhishek Sah
  • 88
  • 2
  • 8