Search code examples
javascriptes6-promisefetch-api

Adding implicit return to arrow function using fetch api


I am playing around with promises and the Fetch API in Javascript

I wanted to know why when I do not add an implicit return in my countryDetail() function, I get undefined, whereas when I add an implicit return I get the data I am looking for?

Here is the function without the implicit return which returns undefined.

const countryDetail = (countryCode) => {
  return fetch("http://restcountries.eu/rest/v2/all")
    .then((response) => {
      if (response.status === 200) {
        return response.json();
      } else {
        throw new Error("Unable to fetch data");
      }
    })
    .then((data) => data.find((country) => country.alpha2Code === countryCode);
};

Here is the same function with the implicit return using the arrow function. This function works and return the data instead of undefined

const countryDetail = (countryCode) => {
  return fetch("http://restcountries.eu/rest/v2/all")
    .then((response) => {
      if (response.status === 200) {
        return response.json();
      } else {
        throw new Error("Unable to fetch data");
      }
    })
    .then((data) => {
      return data.find((country) => country.alpha2Code === countryCode);
    });

here is how the function is being used in app.js

countryDetail("MX")
  .then((country) => {
    console.log(country.name);
  })
  .catch((err) => {
    console.log(err);
  });

Solution

  • It seems, there is a syntactical error in the implicit code. Closing bracket is missing.

    .then((data) => data.find((country) => country.alpha2Code === countryCode);
    

    It should be

    .then((data) => data.find((country) => country.alpha2Code === countryCode));