Home > Net >  API fetch in React
API fetch in React

Time:08-17

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related