I don't know why this isn't updating. I'm relatively new to Svelte but I know about force updating objects arrays with the thing = thing method.
Still, I'm not sure why this doesn't re-render whatsoever? I had this as a Matrix first of all and I thought maybe there was some nestedness that was breaking it but now this is literally just a flat array. It's updating on the matrix on click but not triggering re-render.
<script>
import Nested from './Nested.svelte';
let matrix = new Array(9).fill(null)
let turn = 0
let handleChange = (index) => {
if (matrix[index] != null) return
let newColor = turn % 2 == 0 ? 'red' : 'blue'
matrix[index]= newColor
turn++
matrix = matrix
}
</script>
{#each matrix as team, index}
<Nested team={team} index={index} click={handleChange}/>
{#if (index==2 || index==5)}
<br />
{/if}
{/each}
Nested Component:
<script>
export let index;
export let click;
export let team;
let color = 'white';
if (team) color = team;
</script>
<style>
div {
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
margin: 0;
}
</style>
<div style="background-color: {color}" on:click={(e)=>click(index)}>
{color}
</div>
When working with Svelte, an important thing to keep in mind is that the code in the script
block is only execution when the component is created.
In your case, this means that the line if (team) color = team;
only runs once (at instantiation) and never again afterwards.
If you want something to be re-executed, you have to declare it reactive using $:
For you that would become
$: if (team) color = team
This will be re-executed whenever any of the variables used (team and color) changes.
Note that you can also simply mark a variable to be reactive (Svelte injects the let for you)
export let index;
export let click;
export let team;
$: color = team ?? 'white'