javascript - React Native API Fetch -


i'm trying use fetch api in react native using following code snippet. whenever try console.log api data array comes 'undefined'?!?!

home.js

import api '../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; 

the problem here using componentwillmount fetch data. check these part of docs:

componentwillmount() invoked before mounting occurs. called before render(), therefore setting state in method not trigger re-rendering. avoid introducing side-effects or subscriptions in method.

this lifecycle hook called on server rendering. generally, recommend using constructor() instead.

basically, need use componentdidmount. see here:

componentdidmount() invoked after component mounted. initialization requires dom nodes should go here. if need load data remote endpoint, place instantiate network request. setting state in method trigger re-rendering.

by way, if doing way (directly component) need make sure handle case response comes , component has been unmounted. in case, can use componentwillunmount cancel requests before component unmounted.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -