0

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?

1
  • While I am not into svelte, one query from my side is, what will be returned from statement "$state.value.pop()", is it an array? Commented Mar 3, 2024 at 0:26

1 Answer 1

1

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
}

REPL

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

1
  • I found out that the issue on my end was this reactive declaration on another part of the code $: $store, state.value[1] = 'e'; preventing the removal of the changed item in the array. Thank you
    – fm84
    Commented Mar 3, 2024 at 8:01

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.