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?
question from:
https://stackoverflow.com/questions/65836112/getting-undefined-when-updating-array-in-stores-using-svelte 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…