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

148
Views
API fetch in React

the screenshots attached are the result of an API fetch (movie database). From this results, as shown in the screenshots i am trying to reach for the "primaryImage.url" yet I keep on getting "Cannot read properties of undefined (reading 'url').

Here is my page:

const SearchPage = () => {
  const params = useParams();
  const { query } = params;

  const [data, setData] = useState(null);

  const fetchData = () => {
    fetch(`${rapidApiUrl}/search/title/${query}${rapidSearchData}`, rapidApiOptions)
      .then((response) => response.json())
      .then((data) => {
        setData(data.results);
      })
      .catch((err) => console.error(err));
  };

  useEffect(() => {
    fetchData();
  }, [query]);

  console.log(data)

  return (
    <div>
      {data &&
        data.map((media) => (
          <div key={media.id}>
            {/* <img src={media.primaryImage.url} alt={media.titleText.text} /> */}
            <p>{media.titleText.text}</p>
            <p>{media.releaseYear.year}</p>
          </div>
        ))}
    </div>
  );
};

export default SearchPage;

results promise the array

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

As you are looping through the data, some of the primaryImage values are objects, which do indeed have a url property, but some of them are null. When attempting to find the url property of null, it errors out. You probably want to check to see if primaryImage is null and handle it differently than if it has a value.

about 4 years ago · Santiago Trujillo Report

0

The problem is primaryImage property appears to be null for few cases. You should use optional chaining to avoid the errors.

return (
    <div>
      {data &&
        data.map((media) => (
          <div key={media.id}>
            <img src={media.primaryImage?.url} alt={media.titleText?.text} /> */}
            <p>{media.titleText.text}</p>
            <p>{media.releaseYear.year}</p>
          </div>
        ))}
    </div>
  );

You can read more about optional chaining here

about 4 years ago · Santiago Trujillo 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!