←Back

Executing a function when a certain variable changes (Similar to Vue useEffect or react Watchers);

image.png

E.g. in Add.Svelte, if the errors object from the backend changes, we want to set open to true and open a dialog that indicates what is wrong.

Or another example;

 $effect(() => {
        if ($form.avatar && !$form.processing && preventEffect == false) {
            if (typeof form.avatar === 'string') {
                // If avatar is a filename, set the image source directly
                image.setAttribute('src', $form.avatar);
            } else if (form.avatar instanceof Blob) {
                // If avatar is a Blob, read it as Data URL
                reader.readAsDataURL($form.avatar);
            }
        }
    });

When $form.avatar changes, we want to either read the avatar file contents and use this as a background image, or we want to read the image url of form.avatar (probably not very good architecture to use this as a single varibale.. but anyway), and let the image element point to that url

In legacy mode, use $;

$: {function}

Say, you start to get a very complex file with loads of variables and functions, or are losing overview when passing props between components, it can be very useful to ****separate complex app logic and create a global store