Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch returns undefined when imported

I have a function that fetches data from the url and is supposed to return it:

const fetchTableData = () => {
fetch('https://api.myjson.com/bins/15psn9')
    .then(result => result.json())
    .then(data => {
        return data;
    })
}

export default fetchTableData;

The problem is that when i import this function and try to use it, it always returns undefined.

When i console log the data inside the function itself, you can see it is available. The function just doesn't work when i try to import it.

What is the problem here? Why does it work that way?

like image 535
shakhbulatgaz Avatar asked Nov 21 '18 12:11

shakhbulatgaz


1 Answers

Try this =) You have to return something from the fetchTableData function also.

const fetchTableData = () => {
  const fetchedData = fetch('https://api.myjson.com/bins/15psn9')
    .then(result => result.json())
    .then(data => {
        return data;
    })

    return fetchedData;
}

export default fetchTableData;

Or you can just return it like this:

const fetchTableData = () => {
      return fetch('https://api.myjson.com/bins/15psn9')
        .then(result => result.json())
        .then(data => {
            return data;
        })
    }

    export default fetchTableData;
like image 158
weibenfalk Avatar answered Sep 24 '22 16:09

weibenfalk