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:
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