Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to initialize use the reactive declaration of Sveltejs with array element?

I have an array of units:

let units = ['mm', 'cm', 'm', 'km', 'in', 'yd', 'ft-us', 'ft', 'mi'];

And I want to make a reactive property that changes when the array changes. Something like this:

$: unit = units[0]

function changeUnits(){
    units = ['rad', 'deg', 'grad'];
}

The idea here is to retrieve the first value of the units array every time it changes. So the initial value of unit is mm and after the changeUnits() function the is called the new value should be rad but instead the value of unit unit is undefined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m new to svelte with a reactjs background so I’m unable to wrap my head around this concept. Any help would be appreciated and thanks

>Solution :

This will work for the most part but there is a pitfall here in the execution order of reactive statements: They only update with the component update cycle.

I.e. the variable will be undefined until the first update runs (demonstration).

With this source code:

let units = ['mm', 'cm', 'm', 'km', 'in', 'yd', 'ft-us', 'ft', 'mi'];
$: unit = units[0]

function changeUnits(){
    units = ['rad', 'deg', 'grad'];
}

You get this output:

let unit; // <- undefined at first
let units = ['mm', 'cm', 'm', 'km', 'in', 'yd', 'ft-us', 'ft', 'mi'];

function changeUnits() {
    $$invalidate(2, units = ['rad', 'deg', 'grad']);
}

$$self.$$.update = () => {
    if ($$self.$$.dirty & /*units*/ 4) {
        $: $$invalidate(0, unit = units[0]); // <- assignment happens here
    }
};

So if you want to use the unit in the script right away, you may have to work around this by e.g. doing something like this:

let unit = units[0];
$: unit = units[0];

(These workarounds will not be necessary in Svelte 5.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading