Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to return the result of a function from another page in react native which performing a fetch call. I use the method as follows. As I know this is because asynchronous call. Is there a special way to achieve this in react native ?

fetchcall.js

import address from '../actions/address'
const dashboard = {
  getvals(){

    return fetch(address.dashboardStats(),
    {method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify( {...
      }),
    })
    .then((response) => response.json())
    .then((responseData) => {
      console.warn(responseData);
      return responseData;

    })
    .catch((error) => { console.warn(error); })
    .done();
    // return 'test_val'';
  }
}

export default dashboard;

dashboard.js

import dashboard from '../../services/dashboard';
class Dashboard extends Component {


  componentDidMount(){
      console.warn(dashboard.getvals());
  }

}

export default connect(mapStateToProps, bindAction)(Dashboard);

Its display the result as "undefined", but that fetch call works and it displays the result. Any suggestion?

like image 861
Dinith Minura Avatar asked Jun 20 '17 04:06

Dinith Minura


People also ask

How do you return a value from a fetch?

Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

How do you use Fetch With react native?

In React Native, you can request data from an API over the network using the fetch() method. The syntax is simple as follows: fetch('https://examples.com/data.json'); We simply pass the URL to the fetch method to make a request.


2 Answers

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));
like image 113
Dani Akash Avatar answered Oct 12 '22 00:10

Dani Akash


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.

like image 36
Chris Avatar answered Oct 11 '22 23:10

Chris