user6898463
user6898463

Reputation:

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?

Upvotes: 7

Views: 18339

Answers (3)

Willem van der Veen
Willem van der Veen

Reputation: 36580

In your code you were not returning from the fetchTableData function. Only from the the second then() callback. When a function has no return value, undefined will be returned.

Try this instead:

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

export default fetchTableData;

What now happens is the following:

  1. The response return by the second then() function is returning the data.
  2. We are saving this data in a variable, named myResponse.
  3. We are now returning this value from the function fetchTableData.

Upvotes: 3

weibenfalk
weibenfalk

Reputation: 892

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;

Upvotes: 9

Varit J Patel
Varit J Patel

Reputation: 3520

You need to either store data in a global variable or assign any variable to fetch to get return data.

//First way
fetch('https://api.myjson.com/bins/15psn9')
    .then(result => result.json())
    .then(data => {
        console.log("data",data);
    });
    
//Second way
let binData = null;

fetch('https://api.myjson.com/bins/15psn9')
    .then(result => result.json())
    .then(data => {
        binData = data;
        console.log("binData", binData);
    });
    

Here is the working example.

Upvotes: 3

Related Questions