22

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Dinith Minura
  • 1,446
  • 2
  • 12
  • 24
  • Are you sure it is `getTestval` and not `getvals`? – akond Jun 20 '17 at 05:07
  • @akond, Sorry for that, It was a mistake when editing the question. I edited it now. – Dinith Minura Jun 20 '17 at 05:12
  • I see that you are using react-redux connect, but i dont see mapStateToProps definition at all. Are you even using it at all? Would you consider a solution without redux? – Mμ. Jun 20 '17 at 05:15

3 Answers3

61

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));
Dani Akash
  • 6,828
  • 3
  • 35
  • 47
  • 1
    Sorry, I know this is old now but why the `console.warn()` before returning `responseData`. Is there something wrong with returning that or is it supposed to be a `console.log()`? – Eli Nathan Feb 26 '19 at 09:37
  • It should be `console.log()`. I'll change it. – Dani Akash Feb 26 '19 at 13:48
  • Pls tell me how to pass and i want to export function getvals(){ return fetch('http://xxx'') .then((response) => response.json()) .then((json) => { return json.products; }) .catch((error) => { console.error(error); }); } getvals().then(response => response); const ProductsList =getvals().then(response => response); export default ProductsList; – Yabaz Thampi Jul 15 '20 at 11:06
  • the `return fetch` is ok but the other `return responseData` statement inside `then` is wrong and won't work! – S.Serpooshan Jul 23 '21 at 07:17
8

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.

Chris
  • 119
  • 1
  • 3
2

fetch always return a Promise doesn't matter what you are returning. so you can return a string, variable or something else but you have to use .then to access data

file where you make fetch request

export const graphql = () => {
  return fetch("https://graphqlzero.almansi.me/api", {
    "method": "POST",
    "headers": { "content-type": "application/json" },
    "body": JSON.stringify({
      query: `{
      user(id: 1) {
        id
        name
      }
    }`
    })
  })
    .then((res) => res.json()).then((responseData) => {
      console.log(responseData);
      return responseData;
    })


}

file where you call function

 graphql()
 .then((e) => {
     console.log("data", e)
  });
Shadab Ali
  • 369
  • 3
  • 10