Search code examples
sveltesveltekit

Executing functions on click is not working in sveltekit


I follow a tutorial how to create toast messages. I have to bind the message to the addToast method when I click the submit button. If you look at these two lines of code.

    <button on:click={console.log(form?.message)}>Login</button>
    <button on:click={() => addToast({ form?.message })}>Login</button>

There is not much of a difference, but the first one works perfectly, while the other one returns an error that the keyword form is an unexpected token.. What is the difference between them and why doesn't it work like the console.log?

This is the addToast method:

import { writable } from "svelte/store";

export const toasts = writable([]);

export const addToast = (toast) => {
    const id = Math.floor(Math.random() * 5000);

    const defaults = {
        id,
        type: 'success',
        dismissible: true,
        timeout: 5000
    };

    toasts.update((all) => [{ ...defaults, ...toast}, ...all]);

    if (toast.timeout) setTimeout(() => dismissToast(id), toast.timeout);
}

export const dismissToast = (id) => {
    toasts.update((all) => all.filter(t => t.id !== id ));
}

Solution

  • addToast({ form?.message }) is not valid javascript.

    If you need to pass an object with a key named message to addToast, do so:

    addToast({ message: form?.message })