Return the result value with fetch call function from another page, React native

The best architectural pattern, I think, is to use a callback function, usually by writing in as an anonymous function.

///Component.js
my_service.login((data=>{
  this.setState({body: data.body});
}));

////Service.js
export  const login = function (cb){
  fetch('http://myapi.com/103?_format=hal_json')
    .then((response) =>{
      return response.json();
    })
    .then((data) =>{
      cb(data);
    });
}

I am still a junior developer, but use this pattern frequently. If someone has a reason for a different approach, I would love to hear it.


In fetchcall.js you are returning a Promise. Also since you are returning the responseData in the .then() method itself, you don't need the .done() method.

Since getvals() is returning a Promise, you need to access it's value in a .then() method.

Overall, your code should be like this:

  function getvals(){
    return fetch('https://jsonplaceholder.typicode.com/posts',
    {
    	method: "GET",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    })
    .then((response) => response.json())
    .then((responseData) => {
      console.log(responseData);
      return responseData;
    })
    .catch(error => console.warn(error));
  }
  
  getvals().then(response => console.log(response));