Estoy tratando de hacer una llamada axios en un componente funcional de reacción, pero el ciclo de vida me está dando dolor de cabeza, ya que continuamente devuelve "no se puede leer la propiedad de undefined". Intenté usar la representación condicional, así como la función await/async, pero nada parece funcionar. ¿Alguien podría decirme por favor qué estoy haciendo mal? Gracias
import axios from "axios"; import { useParams } from "react-router-dom"; const SingleCountry = () => { let params = useParams(); const [singleCountry, setSingleCountry] = useState([]); useEffect(() => { const getSingleCountry = () => { axios .get(`https://restcountries.com/v3.1/name/${params.name}`) .then((country) => setSingleCountry(country.data)) .catch((error) => console.log(`${error}`)); }; getSingleCountry(); }, []); return ( <div> <h1>Single Country</h1> {singleCountry.length > 0 && ( <div> <h3>{singleCountry.name.common}</h3> </div> )} </div> ); }; export default SingleCountry;Su método de representación está tratando de acceder a singleCountry.name.common , sin embargo, su variable de estado es una matriz.
Cambie su función de renderizado a:
{singleCountry.map(country => <div><h3>{country.name.common}</h3></div>)}