Assume the following state object:
const state = writable({});
$state = {value: ['a','b','c'], label: 'test'};
And replace one specific item of the array like this:
$state.value[1] = 'e';
Ok, no big deal so far. But then when I want to remove the last item of that array, like this:
const removeLastItem = function () {
$state.value = $state.value.pop();
}
The above works until the changed item of the array is reached (i.e., only one iteration works in this example, so only the last 'c' value is removed, whereas the second and newly updated 'e' value seems impossible to remove).
Note that this behaviour only happens when an update to the array items occurs. Shall I use the spread operator to assign/replace the second value of the array?
pop
returns the removed item, not the remaining items.
You are replacing what was an array with said removed item.
Any further function calls will result in a runtime error since you call pop
on a number.
You probably would want something like this:
const removeLastItem = function () {
$state.value.pop();
$state = $state; // force update
}
(The dummy assignment is necessary in Svelte 3/4 as reactivity is based on assignments.)
The replacement of the element at index 1 should have no effect on any of this.