Creating a toast component using svelte and sveltekit
Tags: javascript, webdev, svelte, sveltekit
Published: 2022-08-24 20:46:00

Read if:
- You wanna learn about svelte stores

Resources:
- [Joy of code's Svelte State Management Article](https://joyofcode.xyz/svelte-state-management#svelte-stores)
- [Joy of code's Svelte State Management Stackblitz](https://stackblitz.com/github/joysofcode/svelte-state-management?file=src%2Flib%2F04-stores%2Findex.svelte,src%2Froutes%2F%2Bpage.svelte,src%2Flib%2F04-stores%2Fnotifications.ts,src%2Flib%2F04-stores%2Ftoast.svelte)
- [How to Build a Custom Alert Component Using SvelteKit and TailwindCSS by James Q Quick](https://www.youtube.com/watch?v=AeOn4YdN7JM&t=319s)

> I have learnt everything from above mentioned resources so if you wanna better understand everything in detail please check them out. 

**Introduction**

This article gonna contain some basics of svelte store and then we going to make a notification/toast component. 

**Svelte/Store**

- The [`svelte/store`](https://svelte.dev/docs#run-time-svelte-store) module exports functions for creating `readable`, `writable` and `derived` stores. 

- Stores are accessible globally. 

- You can access as reactive `$store` syntax or using [`store contract`](https://svelte.dev/docs#component-format-script-4-prefix-stores-with-$-to-access-their-values-store-contract).

**Writeable Store**

- These stores can be manipulated from outside the component and it's created with additional set and update methods.
```Javascript 
store = writable(value?: any)
```

- Set is a method that takes one argument which is the value to be set. The store value gets set to the value of the argument if the store value is not already equal to it.

- Update is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.

```Javascript 
// import writable from svelte store
import { writable } from 'svelte/store';

// Assign a variable to store
const count = writable(0);

// Adding subscribers to store
count.subscribe(value => {
	console.log(value);
}); // logs '0'

// Setting a new value to store
count.set(1); // logs '1'

// Updating store using set value
count.update(n => n + 1); // logs '2'
```

**Readable**
- These stores cannot be manipulated from outside the component.
```Javascript 
store = readable(value?: any, start?: (set: (value: any) => void) => () => void)
```
This is how we create a readable store.

```Javascript 
const time = readable(null, set => {
	set(new Date());

	const interval = setInterval(() => {
		set(new Date());
	}, 1000);

	return () => clearInterval(interval);
});
```

**Derived Stores**

- Derives stores are little bit different from other two. Derived stores uses other stores and then return the call back.

```Javascript 
import { derived } from 'svelte/store';

const doubled = derived(number, $number => $number * 2);

```

As you can see it's using a store `number` then returned it's double, so if number changes so the derived store too.


> This is some basic understanding of svelte stores now we gonna use svelte store to make a notification/toast component.

**Toast Component**
- Here first we going to make a notification store then toast method is going to update the notifications and the removeToast method is going to remove the last notification using after 2 seconds.

```typescript
// lib/notification.ts

import { writable } from 'svelte/store'

type Notification = string

export const notifications = writable<Notification[]>([])

export function toast(message: string) {
  notifications.update((state) => [message, ...state])
  setTimeout(removeToast, 2000)
}

function removeToast() {
  notifications.update((state) => {
    return [...state.slice(0, state.length - 1)]
  })
}
```
- Now we gonna make a component which going to use svelte store that we created above.

```html
<script lang="ts">
  import { fade } from 'svelte/transition'
  import { notifications } from './notifications'
</script>

{#if $notifications}
  <div class="notifications">
    {#each $notifications as notification}
      <div
        role="alert"
        class="notification"
        transition:fade
      >
        {notification}
      </div>
    {/each}
  </div>
{/if}
```
> Above we are looping through are notification store and displaying the available notifications on the screen.

- Now we going to use that component in our project.
```html
<script lang="ts">
  import Toast from './toast.svelte'
  import { toast } from './notifications'
</script>

<Toast />

<button on:click={() => toast('🔥 Svelte is fire')}>
  Show notification
</button>
```
> Above we imported our toast component and toast method from notification to update the store and displaying the toast.

It's a basic toast for explaining store, you can use james q quick's video tutorial for which is in-depth explanation of making a toast.
 
This is me writing for you. If you wanna ask or suggest anything please put it in comment.

**Reason for Late Post**

I was vibing to this song on loop while writing this article 😂

{% embed https://www.youtube.com/watch?v=zQDAi8tI-cU&list=RDzQDAi8tI-cU&start_radio=1 %}