Psionman
Psionman

Reputation: 3677

How to get Svelte reactivity to display changes to array

I am attempting to get Svelte to react to changes in an array. In my example REPL the array is changed, but the html output does not reflect this. What should I do?

<script>
    $: objs = [] || getObjects(objs);

    function update(){
        getObjects(objs);
    }

    function getObjects(objs) {
        objs.push('a');
        objs = objs
        console.log(objs);
        return objs;
    }
</script>

<h1>Lists</h1>
{#each objs || [] as obj}
    <div>
        { obj }
    </div>
{/each}
<button on:click={update}>Update</button>

Upvotes: 2

Views: 5620

Answers (1)

Laaouatni Anas
Laaouatni Anas

Reputation: 3817

by seeing here in this docs: https://svelte.dev/tutorial/updating-arrays-and-objects

we can see for making reactive we have these 2 forms:

  • old way
objs.push("a");
objs = objs;
  • ES6 spread syntax:
objs = [...objs, "a"];

and there isn't any need for extra assignments = [], || that create those bugs, for me the easiest way is this:

<script>
  let objs = []

  function update() {
    objs = [...objs, "a"];
  }
</script>

<h1>Lists</h1>

{#each objs as obj}
  <div>{obj}</div>
{/each}

<button on:click={update}>Update</button>

don't use always $: unless you have 2 or more data calculations or something that changes often in relation to another variable.

in this situation, a simple let variable is enough here since we change only the same variable.

Upvotes: 5

Related Questions