I'm following the Svelte tutorial at https://learn.svelte.dev/tutorial/keyed-each-blocks and there is this example for keyed each blocks :
App.svelte :
<script> import Thing from './Thing.svelte'; let things = [ { id: 1, name: 'apple' }, { id: 2, name: 'banana' }, { id: 3, name: 'carrot' }, { id: 4, name: 'doughnut' }, { id: 5, name: 'egg' } ]; function handleClick() { things = things.slice(1); }</script><button on:click={handleClick}> Remove first thing</button>{#each things as thing (thind.id)}<Thing name={thing.name} />{/each}
Thing.svelte :
<script> const emojis = { apple: '🍎', banana: '🍌', carrot: '🥕', doughnut: '🍩', egg: '🥚' }; // the name is updated whenever the prop value changes... export let name; // ...but the "emoji" variable is fixed upon initialisation // of the component because it uses `const` instead of `$:` const emoji = emojis[name];</script><p>{emoji} = {name}</p>
The purpose of this page is to use the keyed each block {#each things as thing (thind.id)} ... {/each}
. But I don't understand what is the purpose of doing this, as there is a really simple solution with using a reactive declaration : $: emoji = emojis[name];
instead of const emoji = emojis[name];
. My questions are :
Is using a keyed each block useful only to have const
variables ?
Or it can also be a solution when, let's say we have a lot of variables and we dont want to declare them in a reactive way.
What's the best solution to use ?
Thanks