Skip to content

counter for state update #13672

Answered by brunnerh
shevernitskiy asked this question in Q&A
Oct 18, 2024 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

$inspect is just for observing state and only exists during development.
You probably would want to use a regular $effect in combination with $state.snapshot, e.g.

<script>
	import { untrack } from 'svelte';

	let data = $state([]);
	let counter = $state(-1);

	$effect(() => {
		const value = $state.snapshot(data);
		const newCount = untrack(() => counter) + 1;
		counter = newCount;

		if (newCount == 0)
			return;

		console.log("state", value, newCount);
	});
</script>

<button onclick={() => data.push(data.length)}>+</button>
<div>{JSON.stringify(data)}</div>

{#if counter}
	<div>updates: {counter}</div>
{/if}

REPL

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@shevernitskiy
Comment options

Answer selected by shevernitskiy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants