1

I am calling an api from the component, since it looked ugly, thought of moving it out, this is what i tried:

Before:(in the component)

fetch(url)
.then(response => response.json())
.then(data => this.setState({data, loading: false}));

After:

Instead of putting the fetch in the component, i moved it to another function:

export function getData ( url) {
    fetch(url)
    .then(response => response.json())
    .then(data => {
        return data;
    })
}

and i am calling getData(url) from the component, but something is not right, i am not seeing any error, but it does not work

Any thoughts ?

Linschlager
  • 1,539
  • 11
  • 18
Parameswar
  • 1,951
  • 9
  • 34
  • 57
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Quentin May 15 '19 at 14:01

1 Answers1

4

It doesn't work because you're not actually returning anything in getData. The return in the arrow function does not return the overlaying function but just the arrow function.

You could do something like this to work around it:

export function getData ( url) {
    return fetch(url).then(response => response.json())
}

and work with the returned promise like so:

getData("http://...").then(result => console.log(result))
Linschlager
  • 1,539
  • 11
  • 18