Home > Software design >  React: ReviewDetails.js:29 Uncaught TypeError: Cannot read properties of null (reading 'url
React: ReviewDetails.js:29 Uncaught TypeError: Cannot read properties of null (reading 'url

Time:04-04

I'm trying to display the image per ID from my Strapi backend but when I run it in my frontend (ReactJS), it displays this error in my console:

This is my code:

import React from "react";
import { useParams } from "react-router-dom";
import useFetch from "../hooks/useFetch";

export default function ReviewDetails() {
  const { id } = useParams();
  const { loading, error, data } = useFetch('http://localhost:1337/api/reviews/'   id   '/?populate=*')
  const image = useFetch(`http://localhost:1337/api/upload/files/`   id);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  console.log(image);
  console.log(data);

  return (
    <div className="review-card">
      <div className="rating">{data.data.attributes.rating}</div>
      <h2>{data.data.attributes.title}</h2>

      <small>console list</small>

      <p>{data.data.attributes.body}</p>

      <img
        width="500px"
        src={`http://localhost:1337`   image.data.url}
        alt="Not Working!"
      />
    </div>
  );
}

Btw, sometimes it loads when I edit the code but when I refresh it, it doesn't load the image anymore.

CodePudding user response:

The fetch API is asynchronous, so I'm assuming your useFetch hook sets the return value asynchronously. Therefore the image must be fetched on first load, and before the API has returned a response, the returned value will be empty. In other words, image.data will be null, resulting in the error Cannot read properties of null (reading 'url'). This also explains why the image loads after editing the code but not on first refresh.

To solve this error you can use optional chaining:

<img
  width="500px"
  src={`http://localhost:1337${image.data?.url}`}
  alt="Not Working!"
/>

The image still won't load properly until the data has been fetched from the API, but this will prevent any errors. If you have a placeholder URL you can use while the image data is still loading, you can use it like this:

<img
  width="500px"
  src={image.data?.url ? `http://localhost:1337${image.data?.url}` : placeholderURL}
  alt="Not Working!"
/>
  • Related