Form's nested field does not make the img display properly

Problem description: In add-raw-dialog component, there is an image upload function, and it references the sub-component item-image to realize the function, but now the image cannot be previewed normally after uploading. In item-form, item-image is also referenced to realize the same function, but item-form images can be displayed normally.

The git repository for the code in question is [GitHub - liugan2222/demo], and the associated components is
[(demo/components/add-dialog/add-raw-dialog.tsx at master · liugan2222/demo · GitHub) (demo/components/form/item-form.tsx at master · liugan2222/demo · GitHub) (demo/components/common/item/item-image.tsx at master · liugan2222/demo · GitHub)]

Note: There are some differences between the repository code and my local code (the code snippet below is my local code), but the problem in [add-raw-dialog] with the image not loading properly after uploading is the same.

》》》》》》》》》》》》》》》
img is not loading the code properly【for add-item】:
Parent Component References:
<ItemImage
form={form}
isEditing={true}
fieldName={items.${index}.smallImageUrl}
onImageChange={async (file) => {
try {
form.setValue(items.${index}.smallImageUrl, “uploading…”)
const pictureObj = await uploadFile(file)
form.setValue(items.${index}.smallImageUrl, pictureObj.data.id, {
shouldDirty: true,
shouldValidate: true
})
} catch (error) {
form.setValue(items.${index}.smallImageUrl, null)
form.setError(items.${index}.picture, {
type: ‘manual’,
message: error instanceof Error ? error.message : ‘File upload failed’
})
}
}}
/>

Subcomponent handling:
const smallImageUrl = useWatch({
control: form.control,
name: fieldName,
exact: true
});

// Update image URL when smallImageUrl changes

useEffect(() => {
if (smallImageUrl === “uploading…”) {
setIsUploading(true)
return
}

setIsUploading(false)
setImageLoaded(false)

if (smallImageUrl) {
  setUniqueKey(Date.now() + Math.random())
  try {
    const baseUrl = `https://fp.ablueforce.com/api/files/${smallImageUrl}/media`
    // Add timestamp to avoid caching
    const cacheBuster = Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
    const newImageUrl = `${baseUrl}?v=${cacheBuster}`
    setImageUrl(newImageUrl)

    // Increment the key to force a complete re-render of the Image component
  } catch (error) {
    console.error("Error setting image URL:", error)
    setImageUrl(DEFAULT_IMAGE)
  }

} else {
  setImageUrl(DEFAULT_IMAGE)
}

}, [smallImageUrl])

{isEditing && (


{/* Always render the AspectRatio container to ensure consistent layout */}

{isUploading ? (



Uploading image…




) : (
<Image
key={image-${uniqueKey}}
src={imageUrl || DEFAULT_IMAGE}
alt=“Item image”
fill
className=“rounded-md object-cover”
crossOrigin=“anonymous”
unoptimized={true} // Add this to bypass Next.js image optimization
priority={true} // Add priority to load the image faster
onLoad={handleImageLoad}
onError={(e) => {
console.error(‘Image load failed:’, imageUrl);
(e.target as HTMLImageElement).src = DEFAULT_IMAGE;
}}
/>
)}

      {/* Position buttons vertically on the right side */}
      {smallImageUrl && !isUploading && (
        <div className="absolute top-2 right-2 flex flex-col gap-2">
          <Button
            type="button"
            size="sm"
            variant="secondary"
            className="h-8 px-2 bg-white/80 hover:bg-white"
            onClick={handleReplace}
          >
            <RefreshCw className="h-4 w-4 mr-1" />
            Replace
          </Button>
          <Button
            type="button"
            size="sm"
            variant="destructive"
            className="h-8 px-2 bg-white/80 hover:bg-white text-destructive hover:text-destructive"
            onClick={handleRemove}
          >
            <Trash2 className="h-4 w-4 mr-1" />
            Remove
          </Button>
        </div>
      )}
    </div>
  )}

img normal loading code【for edit-item】:
Parent Component References:

<ItemImage
  form={form}
  isEditing={isEditing}
  onImageChange={async (file) => {
	try {
	  // 先设置loading状态
	  form.setValue("smallImageUrl", "uploading...")
	  const response = await uploadFile(file)
	  form.setValue("smallImageUrl", response.data.id)
	} catch (error) {
	  form.setValue("smallImageUrl", null)
	  console.error("Error uploading file:", error)
	}
  }}

》》》》》》》》》》》》》》》》》》》》》》》》》
When add-item is uploaded, the image fails to load and display properly after uploading, but the image url is normal when viewed in developer mode [interface uploadFile and form assignments are fine].

“next”: “15.0.3”,
“react”: “^18.2.0”,
“react-hook-form”: “^7.54.2”,
“react-image-crop”: “^11.0.7”,

》》》》》》》》》》》》》》》》》》》》》》》
Please help me to realize that when add-raw-dialog is uploaded, the image can be previewed and displayed properly, thank you very much!

Hey @liugan2222. Could you edit your post so the code is formatted to be easier to read? If you have a public repo or minimal reproducible example, a link to that would be an easier way to share the code.

Thanks a lot for the heads up, I’ll add the relevant git repositories

Waiting for a reply, please let me know how to solve the above problem if you know the solution, thank you very much.

Thanks for sharing the code! Theres a lot going on in this repo that could complicate things. Are you able to reduce it down to the simplest possible reproduction so we can both focus in on just the relevant elements?