Reputation: 484
I am learning Svelte and how to make custom stores using it. I've come across a problem where when I try to update a writable array using update, it causes an undefined error in components that subscribe to the array.
Here is my store where I have a simple array with one element, a string:
import { writable } from 'svelte/store'
export const activeData = writable(["array"])
Here is a component that updates the store. I am simply pushing the word "pushed" to the activeData array:
<script>
import {activeData} from './Store.js'
let handlePush = ()=>{
activeData.update(val=>{val.push('pushed!')
val = val
}
)
}
</script>
<button
on:click={handlePush}>
push
</button>
And then in this app.svelte component, I am subscribing to activeData and hoping to print the elements of the activeData array using Svelte's #each directive:
<script>
import {activeData} from './Store.js'
import Push from './Push.svelte'
</script>
<div>
{#each $activeData as datum}
<p>{datum}</p>
{/each}
{@debug $activeData}
</div>
<Push/>
When I check the console for activeData, I see that it updates by adding "Push!" to the array. However, I then get an error in my app.svelte component saying "Error: {#each} only iterates over array-like objects."
So after updating the array, the array is no longer an array to components subscribing to it.
Any idea why this is happening?
Upvotes: 3
Views: 3563
Reputation: 27
This is how I ended up doing it. Instead of using update, I directly accessed the store value and just manipulated it there.
$activeData = [...$activeData, 'pushed!']
This fixed my issue. I just couldn't get it to work with the update method.
Upvotes: 0
Reputation: 74096
The update callback should return the new value, in your case you'r returning undefined
, try:
activeData.update(val => [...val, 'pushed!'])
Upvotes: 4