counter for state update #13672
Answered
by
brunnerh
shevernitskiy
asked this question in
Q&A
-
I want count component state updates, which will be a part o f render logic. Here is basic sketch: <script>
let data = $state([]);
let counter = $state(0);
$inspect(data).with((type, value) => {
if (type === "update") {
counter++;
console.debug("state", type, value, counter);
}
});
</script>
<div class:hidden={counter > 0}>updates: {counter}</div>
...rest of the html based on data... This approach triggers classic circular dependency. I've tried make |
Beta Was this translation helpful? Give feedback.
Answered by
brunnerh
Oct 18, 2024
Replies: 1 comment 1 reply
-
<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} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
shevernitskiy
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$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.REPL