lorenzodejong / next-sanity-image

Utility for using responsive images hosted on the Sanity.io CDN with the Next.js image component.
MIT License
148 stars 19 forks source link

Catch Image.asset not found error #14

Closed surjithctly closed 2 years ago

surjithctly commented 3 years ago

I'm getting the following error when we pass image.alt but not image.asset. This plugin should send appropriate error when image.asset is not found.

image

In my code, I cannot do the following because hooks cannot call conditionally.

// This won't work
// Not able to call hooks conditionally. 

  if (!image.asset) {
    return null;
  }
 const imageProps = useNextSanityImage(client, image, {
    imageBuilder: CustomImageBuilder
  });
lorenzodejong commented 3 years ago

Could you perhaps clarify in which scenario this occurs, preferably with a code example of how you retrieve the image from Sanity?

lorenzodejong commented 2 years ago

Closing due to inactivity, issue can be reopened if we can get a reproducible case.

surjithctly commented 2 years ago

Hey,

Sorry, missed your comment. It happens when "image" exists but not "image.asset". I had this issue when I added an image caption without adding image.

To Reproduce:

  1. Go to Sanity and create an image field with caption / alt
  2. Now fill the alt & caption, but don't upload any photo
  3. Save & run the plugin
  4. It will throw this error because the image does not have asset.
surjithctly commented 2 years ago

Now, I tried to add an exception in my code for this scenario.

 if (!image.asset) {
    return null;
  }

But now there is another error called: hooks cannot call conditionally.

So, I can't do this error exception in my code. So checking the possibility to check this in the plugin itself.

lorenzodejong commented 2 years ago

Just checked this in the Sanity studio which i use for testing purposes. It looks like i have to select/upload an image before the "Edit details" button becomes visible and i can specify a caption/alt. What does the configuration of your Sanity image field look like?

surjithctly commented 2 years ago

I have isHighlighted trueas per https://www.sanity.io/docs/image-type

So it will be visible all time.

  fields: [
    {
      name: 'caption',
      type: 'string',
      title: 'Caption',
      options: {
        isHighlighted: true // <-- make this field easily accessible
      }
    },
lorenzodejong commented 2 years ago

Thanks for the extensive example. I've just released version 3.1.7 which includes a check for the existence of the image id in order to fix this issue.