DTJ11235
DTJ11235

Reputation: 3

Why is my Svelte project not updating the DOM when using a non-inline function for a boolean array element toggle?

In a Svelte project, attempting to update a boolean array element via a function triggered by an onclick event appears to update the relevant value, but the update is not reflected in the DOM. Doing the same using an inline function updates the DOM as intended. Both scenarios are illustrated here:

<script>
    let array = [{'truth': false}, {'truth': false}];
    
    function toggleTruth(el) {
        console.log("intial val of el is", el.truth);
        el.truth = !el.truth
        console.log("final val of el is", el.truth);
    }
    
</script>
{#each array as element}
<h1 on:click={() => element.truth = !element.truth}>(inline)Truth is {element.truth} (Does what I want)</h1>
<h1 on:click={() => toggleTruth(element)}>(ext function)Truth is {element.truth}(Doesn't do what I want, but based on the console logs something is being updated)</h1>
{/each}

How can I ensure that the non-inline approach results in the DOM being updated as I expect?

What I've done: I've added a function to be called on click events, which negates a boolean element in an array.

Expected behaviour: The DOM reflects the change in the value of the boolean element.

Actual behaviour: The DOM is not updated, but console logging reveals that the array element is being updated.

Upvotes: 0

Views: 57

Answers (1)

Corrl
Corrl

Reputation: 7721

Add an assignment of the array to itself so that the change is registered and the DOM is updated

    function toggleTruth(el) {
        console.log("intial val of el is", el.truth);
        el.truth = !el.truth
        array = array
        console.log("final val of el is", el.truth);
    }

Upvotes: 0

Related Questions