Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
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; 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>)}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!