Skip to content

Commit 4d7bcf3

Browse files
authored
fix: avatar fallback (#929)
1 parent c44e2c7 commit 4d7bcf3

File tree

3 files changed

+15
-5
lines changed

3 files changed

+15
-5
lines changed

.changeset/red-mails-tease.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"bits-ui": patch
3+
---
4+
5+
fix: Avatar should render fallback if src is updated and is `null`/`undefined`

packages/bits-ui/src/lib/bits/avatar/avatar.svelte.ts

+7-4
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ class AvatarRootState {
4141
});
4242
}
4343

44-
loadImage(src: string, crossorigin?: CrossOrigin, referrerPolicy?: ReferrerPolicy) {
44+
loadImage = (src: string, crossorigin?: CrossOrigin, referrerPolicy?: ReferrerPolicy) => {
4545
let imageTimerId: number;
4646
const image = new Image();
4747

@@ -59,9 +59,9 @@ class AvatarRootState {
5959
this.loadingStatus.current = "error";
6060
};
6161
return () => {
62-
clearTimeout(imageTimerId);
62+
window.clearTimeout(imageTimerId);
6363
};
64-
}
64+
};
6565

6666
props = $derived.by(
6767
() =>
@@ -107,7 +107,10 @@ class AvatarImageState {
107107
});
108108

109109
$effect.pre(() => {
110-
if (!this.#src.current) return;
110+
if (!this.#src.current) {
111+
this.#root.loadingStatus.current = "error";
112+
return;
113+
}
111114
// dependency on crossorigin
112115
this.#crossOrigin.current;
113116
untrack(() =>

sites/docs/src/lib/components/demos/avatar-demo.svelte

+3-1
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
import { Avatar } from "bits-ui";
33
44
let loadingStatus = $state<Avatar.RootProps["loadingStatus"]>("loading");
5+
let src = $state<string | null>("/avatar-1.png");
56
</script>
67

8+
<button onclick={() => (src = null)}> Remove src </button>
79
<Avatar.Root
810
bind:loadingStatus
911
class="h-12 w-12 rounded-full border {loadingStatus === 'loaded'
@@ -13,7 +15,7 @@
1315
<div
1416
class="flex h-full w-full items-center justify-center overflow-hidden rounded-full border-2 border-transparent"
1517
>
16-
<Avatar.Image src="/avatar-1.png" alt="@huntabyte" />
18+
<Avatar.Image {src} alt="@huntabyte" />
1719
<Avatar.Fallback class="border border-muted">HB</Avatar.Fallback>
1820
</div>
1921
</Avatar.Root>

0 commit comments

Comments
 (0)