0

I have an array of favorite citys that im trying to retrieve data for each city by looping my array and calling my fetch function. The issue I have is that it only gets the last item in the array and display one weather card instead of one card per favorite city. To fire this I have a click event that calls a function that loops each favorite city and calls the fetch for that city name. By clicking the button multiple times I can get all the citys one by one, but I want to programmatically get all citys in one click.

Here is my code:

//This is my click function and favorites is an array with citys ex. ['New York','Paris','Rome']
const handleFavorites = () => {
props.queryArray(favorites);};

//This is my fetch function where i try to loop with map (I have also tried with forEach)
const handleQueryArray = async queryArray => {
queryArray.map(async query =>{
  let fetchedWeather = await GetWeatherData(query);
  let fetchedForecast = await GetForecastData(query);
  if (fetchedWeather.cod === 200) {
    if (!search.includes(fetchedWeather.name)) {
      setSearch([...search, fetchedWeather.name]);
      let storedWeather = [...weatherData, fetchedWeather];
      let storedForecast = [...forecastData, fetchedForecast];
      setWeatherData(storedWeather);
      setForecastData(storedForecast);
    }
  } else {
    console.log("No data");
  }
})};
Richard L S
  • 33
  • 1
  • 3
  • Functions can return values, these values can be promises as well and promises can be bundled in a Promise.all. So `Promise.all(someArray.map(arrayItem=>{return Promise.resolve(arrayItem)})).then(results=>do something with results)` – HMR Mar 20 '20 at 16:59
  • 2
    In a word, use `await Promise.all([...].map( ...` for array `async/await` https://stackoverflow.com/questions/33438158/best-way-to-call-an-async-function-within-map – keikai Mar 20 '20 at 17:03

0 Answers0