user3461265
user3461265

Reputation: 11

React Native API Fetch

I'm trying to use fetch api in react native using following code snippet. Whenever I try to console.log the API data array it always comes up 'undefined'?!?!

Home.JS

import api from '../components/api';

class Home extends Component {

constructor(props){
 super(props);
 this.state = {
  profile: []
 }
}

componentWillMount(){
 api.getProfile().then((res) => {
  this.setState({
    profile: res.profile
   })
 });
}
render() {
 console.log("Profile: ", this.state.profile); // Console Out API Data
 return (
  <View style={styles.container}>
    <Text style={styles.welcome}></Text>
  </View>
  );
 }
};

API.JS

var api = {
 getProfile(){
    var url = 'https://api.lootbox.eu/xbl/us/Food%20Market/profile';
    return fetch(url).then((res) => res.json());
 }
};

module.exports = api;

Upvotes: 0

Views: 2800

Answers (2)

femotizo
femotizo

Reputation: 1405

i hope its not too late, i had same issue and stumble on your question. all you have to do is change res.profile to res. am sure you dont have profile data in your json responce

 componentWillMount(){
      api.getProfile().then((res) => {
      this.setState({
       profile: res
    })
  });
}

i hope this helps someone in need.

Upvotes: 0

Ferran Negre
Ferran Negre

Reputation: 3801

The problem here is using componentWillMount to fetch data. Check these part of the docs:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

This is the only lifecycle hook called on server rendering. Generally, we recommend using the constructor() instead.

Basically, you need to use componentDidMount. See here:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

By the way, if you are doing it this way (directly into the component) you need to make sure to handle the case where the response comes and the component has been unmounted. In this case, you can use componentWillUnmount to cancel any requests before the component is unmounted.

Upvotes: 2

Related Questions