radix-ui / primitives

Radix Primitives is an open-source UI component library for building high-quality, accessible design systems and web apps. Maintained by @workos.
https://radix-ui.com/primitives
MIT License
15.34k stars 765 forks source link

Unmounting loaded AvatarImage doesn't cause AvatarFallback to render #1767

Open ShukantPal opened 1 year ago

ShukantPal commented 1 year ago

Bug report

Take the following component

<AvatarPrimitive.Avatar>
  {src && <AvatarPrimitive.AvatarImage src={src} />
  <AvatarPrimitive.AvatarFallback>SP</AvatarPrimitive.AvatarFallback>
</AvatarPrimitive.Avatar>

Assume that the avatar image is "loaded". Now if the src is changed to undefined, the image will be unmounted. However, there's no logic in AvatarImage to set the loading status back to "idle": https://github.com/radix-ui/primitives/blob/02b036d4181131dfc0224044ba5f17d260bce2f8/packages/react/avatar/src/Avatar.tsx#L121

That means the loading status will remain "loaded". The fallback won't render after the image unmounts, as a result: https://github.com/radix-ui/primitives/blob/02b036d4181131dfc0224044ba5f17d260bce2f8/packages/react/avatar/src/Avatar.tsx#L110

Current Behavior

Expected behavior

Reproducible example

https://codesandbox.io/s/in0wzp

In this example, I unmount and re-mount the image in a 1s cycle. You can see that the initials show up the first couple of times but after that the avatar goes blank every other second.

Suggested solution

Reset image loading status to idle on image unmount, here:

https://github.com/radix-ui/primitives/blob/02b036d4181131dfc0224044ba5f17d260bce2f8/packages/react/avatar/src/Avatar.tsx#L75

(because there can't be multiple images per avatar AFAIK)

Your environment

Software Name(s) Version
Radix Package(s) @radix-ui/react-avatar 1.1.0
React n/a
Browser n/a
Assistive tech n/a
Node n/a
npm/yarn n/a
Operating System n/a
benoitgrelard commented 6 months ago

It's a bit contrived as I'm not sure why you'd unmount an avatar image in a real life application, but I think that's a fair change request.

toitzi commented 2 months ago

I ran into the same problem, we allow users to uplaod an avatar, but we also allow them to delete the avatar (the changes are reflected instantly - using swr), after the avatar url changes back to null, the fallback is not rendered.

EDIT: If someone stumbles upon this maybe using shadc/ui there is a workarround for this which seems to work here

tonyfarney commented 1 month ago

The same here: we allow user to delete the avatar but then the fallback doesn't render anymore. It's not the intuitive and expected behavior for a fallback.