VladRia
VladRia

Reputation: 1587

Svelte: force to redraw a component

I have an array of graphs' data. These graphs can be added/removed/reordered. The problem is that the components that are already present in document are not redrawn by Svelte.

<script>
    // App.svelte
    import Graph from "./Graph.svelte";

    let arr = [];
    
    function add(n) {
        arr.unshift(n)
        arr = arr
    }
    
    add(1)
    setTimeout(() => add(2), 1000)
    setTimeout(() => add(3), 2000)
</script>

{#each arr as number}
    <Graph {number} />
{/each}
<script>
    // Graph.svelte
    import { onMount } from 'svelte'
    
    export let number
    let graph
    
    function updateCanvas() {
        graph = number
    }
    
    updateCanvas(number)
</script>

<div>{graph}</div>

The result is that I have the first graph drawn three times. This is because it is always the last in the array and it is always the only one to be rendred. How do I force the redraw of each Graph ?

https://svelte.dev/repl/cc2ee63a296342a9b71c715fdb16aca6?version=3.37.0

Thanks in advance.

Upvotes: 0

Views: 1171

Answers (2)

Coolkid123-boop
Coolkid123-boop

Reputation: 33

Methods like pop and unshift do not work when trying to update the screen as clearly stated in the svelte tutorial here. You however can use thisarr = [n,...arr] which worked for me!

Upvotes: 0

dummdidumm
dummdidumm

Reputation: 5426

You need to tell Svelte to rerun updateCanvas on each prop change. Right now updateCanvas(number) is only run once on startup. Making it reactive is as easy as prepending $: (docs reactive assignment here). Fixed code for Graph.svelte:

<script>
    // Graph.svelte
    import { onMount } from 'svelte'
    
    export let number
    let graph
    
    function updateCanvas() {
        graph = number
    }
    
    $: updateCanvas(number)
</script>

<div>{graph}</div>

Upvotes: 3

Related Questions