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.
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.)