i’m trying to create an array of the daily forecast mapping over an array with cities. I’m trying to map over the array of the cities making an api call for each one of them once the page loads. I keep on getting an array of Promises such as this :
Favorite Page component:
const [dailyForeCast, setDailyForeCast] = useState([]); const favorites = [ { Key: '213181', type: 'City', }, { Key: '213121', type: 'City', }, ]; useEffect(() => { const fetchData = async () => { const results = await favorites.map((city) => { return weatherService.getSingleForeCast(city.Key); }); setDailyForeCast(results); }; fetchData(); }, []); console.log('dailyForest:', dailyForeCast);
Service with the api call :
async function getSingleForeCast(value) { try { const res = await axios.get(`http://dataservice.accuweather.com/forecasts/v1/daily/1day/${value}`, { params: { apikey: API_KEY, details: true, metric: true, }, }); const result = res.data.DailyForecasts; return result; } catch { console.log('cant get single forecast'); } }
Would appreciate any help ,thanks in advance 🙂
Advertisement
Answer
As Brian has said you’re not actually awaiting the promises, but the map function.
Try something like this (untested):
const fetchData = async () => { const promises = favorites.map((city) => { return weatherService.getSingleForeCast(city.Key); }); const results = await Promise.all(promises) setDailyForeCast(results); };