'Each block looping through array is not working in svelte
So i have been working on this svelte project which is a notes app. So my goal is that whenever i press the submit button the note gets added to a array and the array get printed out as a each block in svelte. However my array gets updated but not my UI. i have console logged the array every time i press the submit button. I have to added any components yet. You can have a look at my code:
let value = ""
let values = []
function logic(){
values.push(value)
}
</script>
<input type="text" bind:value={value}>
<br>
<button on:click={logic}>Submit</button>
<hr>
{#each values as name, index}
<li>{index} - {name}</li>
{/each}
<style>
input {
height:100px;
width: 200px;
margin-bottom: 1em;
}
button{
height: 50px;
width: 100px;
}
</style>
Hope you find the problem, Thanks in advance
Solution 1:[1]
It looks like your problem is because pushing an item into an array does not trigger Svelte's reactivity. Since a value that is being stored into a variable from an array is just the memory location, Svelte does not detect any change in the variable, because it changes the value of the array not the variable.
The svelte devs recommended to try to reassign the value of an array such like:
<script>
let value = ""
let values = []
function logic(){
// As you can see here, I'm reassigning the array.
values = [...values, value]
}
</script>
<input type="text" bind:value={value}>
<br>
<button on:click={logic}>Submit</button>
<hr>
{#each values as name, index}
<li>{index} - {name}</li>
{/each}
<style>
input {
height:100px;
width: 200px;
margin-bottom: 1em;
}
button{
height: 50px;
width: 100px;
}
</style>
Here's the tutorial that the Svelte docs gave: https://svelte.dev/tutorial/updating-arrays-and-objects
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Catalactics |
