zerodevx/svelte-toast

Feature request: Set max number of toasts

Closed this issue · 5 comments

First of all, THANK YOU! This is such an awesome little library. Compared to some of the other packages that implement toasts, your design around handling multiple toasts is sublime. Also, I love how easy it is to customize styling. I could go on.

I need to set a max number of toasts. Currently, I do it like this:

toast.subscribe((toasts) => {
    if (toasts.length > 5) {
        toasts.pop();
    }
});

But I don't think that's very nice. I'd rather there was something like a all or toasts attribute on toast, which gave a list of toasts so I could do something like:

if (toasts.all.length < 5) {
    toast.push(...)
}

I can of course also keep track of the number of toasts with a global variable, but this is not very nice I think.

Hey, so glad you found this useful! 🎉 Re your question, the toast emitter is in fact just a standard Svelte store (with some additional functions) containing the list of active toasts. You can consume it like how you'd usually use Svelte stores, with reactivity, auto-subscriptions etc. For example:

<script>
import { toast, SvelteToast } from '@zerodevx/svelte-toast'
	
function clicked() {
  toast.push('Hello world!')
}

// $toast is an array of toasts, so
// $toast.length will always hold the count of active toasts
$: if ($toast.length > 5) toast.pop()
</script>

<button on:click={clicked}>Push (toast count is {$toast.length})</button>

<p>List of toasts:</p>

{#each $toast as item}
{JSON.stringify(item)}
{/each}

<SvelteToast />

Here's the REPL: https://svelte.dev/repl/4228aaa63f6b41c9af61b6c33ef7f4c2?version=3.48.0

Ahh brilliant! That solves it for me 🥳!

But I do get a TypeScript error which I think deserves your attention.

In a minimal example like this, in some ".ts" script:

import { toast } from '@zerodevx/svelte-toast';
import { get } from 'svelte/store';

get(toast)

the TypeScript linter complains over the get(toast) line, saying:

Screenshot 2022-05-23 at 06 47 30

It's was the same when I tried to implement my solution using toast.subscribe, and in fact that's also what the error is saying (that subscribe is missing). The strange thing is that when I place a debugger in my code, toast DOES have a subscribe method. And I looked into your code; it's pretty clear that the createToast returns a valid store object with a subscribe key and all.

It's not a Svelte bug I think. I tried something super simple like:

import { get, writable } from 'svelte/store';

function createCount() {
  const { subscribe, set, update } = writable(0);
  return {
    subscribe,
  };
}

let store = createCount();
get(store);

and that did not cause any linting errors.

Note: this is not a blocker, and the code runs just fine.

This should be fixed in v0.7.2.

Awesome. Again, really enjoying your work. Thanks a lot!