Soy nuevo en React, estaba tratando de hacer un sitio web meteorológico. Primero quiero obtener la IP del visitante, luego obtener la ubicación de la ciudad y luego obtener las condiciones climáticas directamente a través de Openweather. Aquí está mi código, espero que alguien pueda ayudarme a responder cómo completar este sitio web, gracias
import { useState, useEffect } from "react"; import axios from "axios"; require("dotenv").config(); function IpGet() { const [ip, setIP] = useState(""); const [countryName, setcountryName] = useState(""); const [cityName, setcityName] = useState(""); const [countryCode, setcountryCode] = useState(""); const [countryStateName, setcountryStateName] = useState(""); const WeatherKey = process.env.REACT_APP_WEATHERKEY; const getData = async () => { const res = await axios.get("https://geolocation-db.com/json/"); setIP(res.data.IPv4); setcountryName(res.data.country_name); setcityName(res.data.city); setcountryCode(res.data.country_code); setcountryStateName(res.data.state); }; // const getWeather = async () => { // const WeatherUrl = await axios.get( // `https://api.openweathermap.org/data/2.5/weather?q=${cityName},${countryStateName}&appid=${WeatherKey}` // ); // }; useEffect(() => { getData(); }, []); return ( <div className="IpGet"> <h4>{ip}</h4> <h4>{countryName}</h4> <h4>{countryCode}</h4> <h4>{countryStateName}</h4> <h4>{cityName}</h4> </div> ); } export default IpGet;La pregunta es vaga, pero aquí hay un poco de suposición.
Algunos consejos para empezar:
setCountryName en lugar de setcountryName .useMemo volverá a calcular esa función. Ahora al código. Puede darle a useEffect el segundo argumento de una matriz de variables. Si alguna de estas variables cambia, el efecto ejecutará la función de devolución de llamada proporcionada como el primer argumento. useEffect también siempre se ejecutará una vez cuando se monte el componente.
Cree un segundo efecto que se ejecute cuando obtenga los datos necesarios para realizar la llamada a la API meteorológica.
Teniendo en cuenta todas las cosas anteriores, su código ahora podría verse así (no probado):
import { useState, useEffect } from 'react'; require('dotenv').config(); function IpGet() { const [ip, setIP] = useState(''); const [countryName, setCountryName] = useState(''); const [cityName, setCityName] = useState(''); const [countryCode, setCountryCode] = useState(''); const [countryStateName, setCountryStateName] = useState(''); const weatherKey = process.env.REACT_APP_WEATHERKEY; // useMemo to avoid recreating this function on every render const getData = React.useMemo(() => async () => { const res = await fetch('https://geolocation-db.com/json/'); setIP(res.data.IPv4); setCountryName(res.data.country_name); setCityName(res.data.city); setCountryCode(res.data.country_code); setCountryStateName(res.data.state); }); const getWeather = React.useMemo(() => async () => { if (!cityName || !countryStateName || !weatherKey) return; const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${cityName},${countryStateName}&appid=${weatherKey}`; const weatherData = await fetch(weatherUrl); // Do something with weatherData here... set to some state or something. }); useEffect(() => { getData(); }); // No dependency array, so this will only run once when the component mounts useEffect(() => { getWeather(); }, [cityName, countryStateName]); // This will trigger the callback when any of these variables change. return ( <div className='IpGet'> <h4>{ip}</h4> <h4>{countryName}</h4> <h4>{countryCode}</h4> <h4>{countryStateName}</h4> <h4>{cityName}</h4> </div> ); } export default IpGet;