I am playing around with the svelte store in the svelte docs envsvelte Stores/autosubscription.
I am actually trying to add objects to an array named scores. My code is the following.
App.svelte
<script>
import { scores } from './stores.js';
import Incrementer from './Incrementer.svelte';
import Decrementer from './Decrementer.svelte';
import Resetter from './Resetter.svelte';
</script>
<h1>The count is:</h1>
{#each $scores as score, i}
<ul>
<li>
name: {score.name}
</li>
<li>
score: {score.score}
</li>
<li>
maxScore: {score.maxScore}
</li>
</ul>
{/each}
<Incrementer/>
<Decrementer/>
<Resetter/>
Incrementer.svelte
<script>
import { scores } from './stores.js';
function increment() {
count.update(n => n.push(n[0]));
}
</script>
<button on:click={increment}>
+
</button>
Resetter.svelte
<script>
import { scores } from './stores.js';
function reset() {
scores.set([{
name: 'name',
score: 1,
maxScore: 1
},{
name: 'anderer',
score: 4,
maxScore: 8
}]);
}
</script>
<button on:click={reset}>
reset
</button>
and finally the stores.js
import { writable } from 'svelte/store';
export const scores = writable([{name: 'NAME', score: 1000, maxScore: 3000}]);
(I left out the Decrementer.svelte which is identically to Incrementer.svelte but implements n.pop)
What my problem is, that the Incrementer and Decrementer do not change the $scores viewed in the Result window.
I've also tried to push an object in the Incrementer.svelte:
function increment() {
count.update(n => n.push({name: 'name', score: 2, maxScore: 3}));
}
The reset code does work as I intended.
Can someone please tell me, what I am missing here?
Thank you!
Where missing some context here
count.update(n => n.push(n[0]));
count isn't defined in any of the snippets, i assume you meant scores.update
The return of the callback passed to update becomes the new value, in case of a push that will be a number (the new length of the array) not the new array.
I expected to see a
scores.update(n => { n.push(n[0]); return n});
// or
scores.update(n => [...n, n[0]]);
// or
$scores = [...$scores, $scores[0]];
To debug a store, write the following line in a component:
$: console.log($scores);