Learning Svelte Part # 5
Table of contents
Arrays & Objects
Hello developers and welcome back to this series about how i am learning Svelte. In today's post i will explain how to update Arrays and Objects, the update happen reactively when we change values.
Let’s try with an example:
First of all, we’re going to declare a new variable called frameworks.
<script>
let frameworks = ["Vue", "React","Angular", "Ember"];
</script>
And we will loop trough it, in th HTML section:
<ul>
{#each frameworks as framework}
<li>{framework}</li>
{/each}
</ul>
Essentially we are creating a new list item for each one out of our Frameworks, the result in our html file:
Now to demonstrate the reactivity we are going to add another item to our list, let’s say after a 3 seconds delay.
To do that we need a new function:
We would expect now to have the last item added to our list, but it's not the case, we need another step before accomplishing the result.
Svelte it's not able to catch the change yet, so it's not reflected inside the list.
To make Svelte to pick up the change we only need to write another line of code on our function, that it's going to work because we will use an equal operator that it's re-assigning the value of frameworks
The new function:
Now the result is the one expected:
Another way to achieve the same result it's using the spread syntax in our variable:
This is the equivalent to using "push", also we use the equal operator.
For the Objects it's the same but just a little bit easier:
This is it for my weekly update, see you next Sunday, until then you can find me on Twitter