Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Не получается забрать данные от fetch (https://javascript.ru/forum/dom-window/78233-ne-poluchaetsya-zabrat-dannye-ot-fetch.html)

cybercoder 13.08.2019 10:23

Не получается забрать данные от fetch
 
function createTownslist() {
    let towns = ["Sudak", "Yalta", "Kerch", "Feodosiya"];
    let townslist = {};
        towns.forEach(town => {
            fetch(`https://api.weatherbit.io/v2.0/current?city=${town}&key=ced73555abfb464ebcb5d7e77f5be270`)
            .then(res => res.json())
            .then(json => townslist[town] = json.data[0])
            }
        )
        return townslist;
    }
    
    console.log(createTownslist());
    
    //     {}
    //      Feodosiya: {rh: 45, pod: "d", lon: 35.37789, pres: 1008.48, timezone: "Europe/Simferopol", …}
    //      Kerch: {rh: 49, pod: "d", lon: 36.47429, pres: 1011.7, timezone: "Europe/Simferopol", …}
    //      Sudak: {rh: 42, pod: "d", lon: 34.97471, pres: 1017.46, timezone: "Europe/Simferopol", …}
    //      Yalta: {rh: 46, pod: "d", lon: 37.27365, pres: 1016.05, timezone: "Europe/Kiev", …}
    //      __proto__: Object
    
    console.log(Object.keys(createTownslist()));

    //      Array(0)
    //      length: 0
    //      __proto__: Array(0)

рони 13.08.2019 10:43

cybercoder,
Promise.all
Параллельное выполнение
или
Асинхронные функции

SuperZen 13.08.2019 10:56

function createTownslist() {
  let towns = ["Sudak", "Yalta", "Kerch", "Feodosiya"];
  return Promise.all(
    towns.map(town => fetch(`https://api.weatherbit.io/v2.0/current?city=${town}&key=ced73555abfb464ebcb5d7e77f5be270`)
      .then(res => res.json())
      .then(json => json.data))
  )
    .then(response => {
      return towns.reduce((acc, town, i) => {
        acc[town] = response[i]
        return acc
      }, {})
    })
}

// createTownslist().then(towns => console.log(Object.keys(towns), towns));

(async function () {
  const towns = await createTownslist()
  console.log(Object.keys(towns), towns)
})()


надо разбираться с асинхронность ) ЯП

https://medium.com/@stasonmars/%D0%B...it-ba5f47f4436

cybercoder 18.08.2019 09:48

SuperZen,
Спасибо. А как можно передать эти данные дочернему компоненту react?

SuperZen 19.08.2019 11:58

import React from 'react'

function ForecastItem({ town, data }) {
  return <React.Fragment>
    <div>
      {town} - {JSON.stringify(data)}
    </div>
    <hr />
  </React.Fragment>
}

function App() {

  const [forecast, setForecast] = React.useState({})

  const memoForecast = React.useMemo(
    () => {
      return Object.keys(forecast).map(forecastKey => (
        <ForecastItem
          key={forecastKey}
          town={forecastKey}
          data={forecast[forecastKey]}
        />
      ))
    },
    [forecast]
  )

  React.useEffect(
    () => {
      let towns = ["Sudak", "Yalta", "Kerch", "Feodosiya"];
      Promise.all(
        towns.map(town => fetch(`https://api.weatherbit.io/v2.0/current?city=${town}&key=ced73555abfb464ebcb5d7e77f5be270`)
          .then(res => res.json())
          .then(json => json.data))
      )
        .then(response => {
          setForecast(towns.reduce((acc, town, i) => {
            acc[town] = response[i]
            return acc
          }, {}))
        })
    },
    []
  )

  return memoForecast
}

export default App


если данные нужны глобально можно использовать https://reactjs.org/docs/context.html


Часовой пояс GMT +3, время: 16:49.