3

Learning Svelte Part # 5

 2 years ago
source link: https://dev.to/alessandrogiuzio/learning-svelte-part-5-ici
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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>
Enter fullscreen modeExit fullscreen mode

And we will loop trough it, in th HTML section:

<ul>
{#each frameworks as framework}
  <li>{framework}</li>
{/each}
</ul>
Enter fullscreen modeExit fullscreen mode

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK