Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting undefined when updating array in stores using Svelte

Tags:

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?

like image 793
rguttersohn Avatar asked Jun 17 '26 17:06

rguttersohn


1 Answers

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

activeData.update(val => [...val, 'pushed!'])
like image 185
CD.. Avatar answered Jun 23 '26 10:06

CD..



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!