Next.js Discord

Discord Forum

Why Does My Variable Always Evaluate as Empty String?

Unanswered
Jersey Wooly posted this in #help-forum
Open in Discord
Jersey WoolyOP
I have this original code at the top of a component:
const [activePreview, setActivePreview] = useState(0);

then this is used for an image later on:
<Image
  src={product?.imgs?.previews?.[activePreview]}
  alt="products-details"
  width={400}
  height={400}
/>

When I preview that page, I get this error:
<Image
^
  src={product?.imgs?.previews?.[activePreview]}
  alt="products-details"
  width={400}

An empty string ("") was passed to the src attribute. To fix this, either do not render the element at all or pass null to src instead of an empty string.

So I tried avoiding the empty string at the top of the component:
  const [activePreview, setActivePreview] = useState(0);
  let imgSrc = product?.imgs?.previews?.[activePreview]; 
  if (imgSrc == "") imgSrc = null;

And then using the empty string proof imgSrc in the image:
<Image
  src={imgSrc}
  alt="products-details"
  width={400}
  height={400}

Yet I still get the exact same error when the an attempt is made to render the image.

I have about 6 months Nextjs now, but I'm a very experience dev overall, and have never had anything like this crop up in an app before. I mean with if (imgSrc == "") imgSrc = null, how can it have a value of empty string when used for src? No other code mofifies this variable between when I ensure it's not empty.

5 Replies

Oak shoot sawfly
​When your component first loads, the product data (the list of images) hasn't arrived yet—it's still undefined.
​When data is undefined, your code
if (imgSrc == "") imgSrc = null; // This check fails!
...doesn't run when imgSrc is undefined.
Crucially, in JavaScript, undefined is not equal to ""
Jersey WoolyOP
Thanks