Alan El-nino Malmsteen Alan El-nino Malmsteen - 3 months ago 180
React JSX Question

React Native get value from promises after fetch data finished

I'm trying to get value from another function that call fetch promises but it returned undefined, i think the problem is the result wouldn't wait the process from called function until it done.

Here is the code:

var myConnection = require('../components/connection');
var RequestToken = React.createClass({
getInitialState: function() {
return {
};
},
componentDidMount: function(){
AsyncStorage.getItem('token').then((value) => {
if(typeof value != null){
this.setState({"token": value});
// call this function
this.catchToken(value);
}
}).done();
},
catchToken: async function(token){

try{
var URL = "http://someurl.com/";
var params = {
token:token
}
let val = await myConnection.now(URL,params);

this.setState({
responseAPI:val
});
// returned undefined
console.error(this.state.responseAPI);
}catch (e){
console.error(e);
}
}
});


and connection.js

function timeout(ms, promise) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error("Connection timeout"))
}, ms);
promise.then(resolve, reject);
});
}
var myConnection = {
now: async function(URL,params){
//return "OK";
var formData = new FormData();
for (var k in params) {
formData.append(k, params[k]);
}
timeout(10000, fetch( URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})).then(
(response) => response.json()
).then((res) => {
// result data
return res;
}).catch((error) => {
console.error(error);
}).done();
}
};
module.exports = myConnection;


Can someone explain how to get returned value after function process is done?

Thanks

Answer

You should handle the promise in this kind of way in the component:

myConnection.now(URL,params)
 .then(val => {
   this.setState({
      responseAPI:val
   });
 })
 .catch(error =>{
   console.error(error);
 });

on the api side you need to return a promise (timeout function in your code):

var myConnection = {
  now: async function(URL,params){
  //return "OK";
  var formData = new FormData();
  for (var k in params) {
      formData.append(k, params[k]);
  }

//You need to return the promise
  return timeout(10000, fetch( URL, {
      method: 'POST',
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'multipart/form-data'
      },
      body: formData
    })).then(
      (response) => response.json()
    ).then((res) => {
      // result data
      return res;
    }).catch((error) => {
      console.error(error);
    }).done();
  }
};

The timeout should either reject or resolve the promise, and it is simpler if the fetch call is inside here:

function timeout(ms, promise) {
  return new Promise(function(resolve, reject) {
  setTimeout(function() {
      reject(new Error("Connection timeout"))
  }, ms);
  fetch( URL, {
      method: 'POST',
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'multipart/form-data'
      },
      body: formData
  })).then(
      (response) => response.json()
  ).then((res) => {
      // result data
      resolve(res);
  }).catch((error) => {
      reject(error);
  }).done();
  });
}