Skip to content

Commit aafddd8

Browse files
committed
fix(useToast): add in queue and improve unique ids
Resolves #2686
1 parent 8d941e1 commit aafddd8

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

src/runtime/composables/useToast.ts

+28-7
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ref, nextTick } from 'vue'
12
import { useState } from '#imports'
23
import type { ToastProps } from '../types'
34

@@ -8,20 +9,40 @@ export interface Toast extends Omit<ToastProps, 'defaultOpen'> {
89

910
export function useToast() {
1011
const toasts = useState<Toast[]>('toasts', () => [])
12+
const maxToasts = 5
13+
const running = ref(false)
14+
const queue: Toast[] = []
1115

12-
function add(toast: Partial<Toast>): Toast {
16+
const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
17+
18+
async function processQueue() {
19+
if (running.value || queue.length === 0) {
20+
return
21+
}
22+
23+
running.value = true
24+
25+
while (queue.length > 0) {
26+
const toast = queue.shift()!
27+
28+
await nextTick()
29+
30+
toasts.value = [...toasts.value, toast].slice(-maxToasts)
31+
}
32+
33+
running.value = false
34+
}
35+
36+
async function add(toast: Partial<Toast>): Promise<Toast> {
1337
const body = {
14-
id: new Date().getTime().toString(),
38+
id: generateId(),
1539
open: true,
1640
...toast
1741
}
1842

19-
const index = toasts.value.findIndex((t: Toast) => t.id === body.id)
20-
if (index === -1) {
21-
toasts.value.push(body)
22-
}
43+
queue.push(body)
2344

24-
toasts.value = toasts.value.slice(-5)
45+
await processQueue()
2546

2647
return body
2748
}

0 commit comments

Comments
 (0)