Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lifecycle issue on axios call to an external API

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; 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading