Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

Getting undefined when updating array in stores using Svelte

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The update callback should return the new value, in your case you'r returning undefined, try:

activeData.update(val => [...val, 'pushed!'])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...