0

I'm new to JS and I'm very confused as to what my function is doing. I have a function getCities declared in my App.js file that returns an array:

export async function getCities() {
  const options = {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' }
  }
  const getData = await fetch("/api", options);

  const cities = await getData.json();

  console.log(cities[0]);
  return cities;
}

I've imported getCities into another file and I'm trying to use this function as an array to populate my options in a React Select dropdown menu.

console.log(Array.from(getCities));
console.log(Array.from(getCities()));

Both of the above logs output empty arrays (I tried both because I'm still fuzzy on JS syntax). When I do

console.log(getCities());

I see this in my console, with all of my cities in there: enter image description here

I think I'm misunderstanding what the getCities function can do. From what I've seen, I should be able to do getCities[0] and see my first city, but this returns "undefined". I thought maybe I need to change getCities from an array of promises to a regular array with the code

export async function myFunction() {
    const options = await Promise.all(getCities);
    return options;
}

But that gave me the error: Unhandled Rejection (TypeError): function is not iterable (cannot read property Symbol(Symbol.iterator)). Does this mean there is an issue with the getCities function as I have it set up? Excuse my rambling, again I'm very new to JS and I've been researching this for a while

  • function `getCities` returns a Promise so `const options = await getCities()` is what you want - of course, when you call `myFunction()` ... you'll either have to `await` that, or use `myFunction().then(result => ... deal with results here ...)` – Jaromanda X Jun 30 '21 at 16:23
  • Your `getCities` function is just fine (other than it may get hit by [this `fetch` API footgun](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html)). It returns a *promise* of the array of cities. To get the cities, you have to use it the same way you used `fetch`: via `await` (or in a non-`async` function, but using `.then` and `.catch` on the promise). See the linked question's answers for details. – T.J. Crowder Jun 30 '21 at 16:24

0 Answers0