Home > OS >  Lifecycle issue on axios call to an external API
Lifecycle issue on axios call to an external API

Time:11-30

I am trying to make an axios call on a react functional component, but the lifecycle is giving me a headache, as it continuously returns "can not read property of undefined". I tried using conditional rendering as well as await/async function, but nothing seems to work. Could someone tell me please what am I doing wrong? Thanks

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; 

CodePudding user response:

Your render method is trying to access singleCountry.name.common, however, your state variable is an array.

Change your render function to:

{singleCountry.map(country => <div><h3>{country.name.common}</h3></div>)}
  • Related