fetchData.js -> Archivo donde buscamos los datos. Este archivo se importa más tarde y las funciones se utilizarán para mostrar los datos obtenidos.
import { weatherAPIConfig } from "../weatherAPIConfig" export async function fetchWeatherForecast(cityName) { let URL = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=metric&appid=${weatherAPIConfig.key}` try { const fetchWeatherForecast = await fetch(URL) const weatherForecastJSON = await fetchWeatherForecast.json() return weatherForecastJSON } catch (error) { console.log("Could not find given city"); return "Could not find given city" } } export function getWeatherDescription(weatherForecastJSON) { return weatherForecastJSON.weather[0].description; } export function getWeatherTemperature(weatherForecastJSON) { return weatherForecastJSON.main.temp } export function getWeatherWindSpeed(weatherForecastJSON) { return weatherForecastJSON.wind.speed; } export function getWeatherHumidity(weatherForecastJSON) { return weatherForecastJSON.main.humidity }Row.js -> El archivo donde se muestra la temperatura, etc. en div
import React from 'react' import {getWeatherDescription, getWeatherHumidity, getWeatherTemperature, getWeatherWindSpeed, fetchWeatherForecast} from '../../functions/fetchData' import { weatherAPIConfig } from '../../weatherAPIConfig'; function Row() { return ( <div> <div>API-key: {weatherAPIConfig.key}</div> <div>Result: {getWeatherDescription(fetchWeatherForecast("London"))}</div> </div> ) } export default Row;.................................................... ......................................
Recomiendo que su función "fetchWeatherForecast" devuelva un objeto con esos métodos disponibles para analizar:
import { weatherAPIConfig } from "../weatherAPIConfig" export async function fetchWeatherForecast(cityName) { let URL = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=metric&appid=${weatherAPIConfig.key}` try { const weatherForecast = await fetch(URL) //changed cuz I don't recommend naming your variable the same as the function const weatherForecastJSON = await fetchWeatherForecast.json() } catch (error) { console.log("Could not find given city"); return "Could not find given city" } function getWeatherDescription() { return weatherForecastJSON.weather[0].description; } function getWeatherTemperature() { return weatherForecastJSON.main.temp } function getWeatherWindSpeed() { return weatherForecastJSON.wind.speed; } function getWeatherHumidity() { return weatherForecastJSON.main.humidity } return {getWeatherDescription, getWeatherTemperature, getWeatherWindSpeed, getWeatherHumidity} }Así que ahora en su "Row.js", puede hacer:
import React from 'react' import {fetchWeatherForecast} from '../../functions/fetchData' import { weatherAPIConfig } from '../../weatherAPIConfig'; const {useEffect, useState} = React; function Row() { var [forecast, setForecast] = useState({}); useEffect(()=>{ fetchWeatherForecast("London").then((forecastObj)=>setForecast(forecastObj)); }, []) return ( <div> <div>API-key: {weatherAPIConfig.key}</div> <div>Result: {forecast.getWeatherDescription?.()}</div> </div> ) } export default Row;Como descargo de responsabilidad, no he probado este código. Pero lo esencial es que el método "fetchweatherForecast" devuelva un objeto con métodos que puedan acceder al objeto "weatherForecastJSON". Luego cree una instancia de este objeto dentro de su "Row.js" y represente los datos con los métodos devueltos por el objeto "weatherForecastJSON".
Editar: como señaló @Patrick Roberts, "forecast.getWeatherDescription ()" generaría un error en el primer renderizado. Para remediarlo, he usado un encadenamiento opcional que llamaría a la función solo si existe en el objeto. La alternativa sería:
<div>Result: {forecast.getWeatherDescription ? forecast.getWeatherDescription() : ''}</div>