Basic Svelte
Introduction
Bindings
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
Stores
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
It’s often useful to be able to track the value of a piece of state as it changes over time.
Inside the addNumber
function, we’ve added a console.log
statement. But if you click the button and open the console drawer (using the button to the right of the URL bar), you’ll see a warning, and a message saying the message could not be cloned.
That’s because numbers
is a reactive proxy. There are a couple of things we can do. Firstly, we can create a non-reactive snapshot of the state with $state.snapshot(...)
:
function addNumber() {
numbers.push(numbers.length + 1);
console.log($state.snapshot(numbers));
}
Alternatively, we can use the $inspect
rune to automatically log a snapshot of the state whenever it changes. This code will automatically be stripped out of your production build:
function addNumber() {
numbers.push(numbers.length + 1);
console.log($state.snapshot(numbers));
}
$inspect(numbers);
You can customise how the information is displayed by using $inspect(...).with(fn)
— for example, you can use console.trace
to see where the state change originated from:
$inspect(numbers).with(console.trace);
<script>
let numbers = $state([1, 2, 3, 4]);
let total = $derived(numbers.reduce((t, n) => t + n, 0));
function addNumber() {
numbers.push(numbers.length + 1);
console.log(numbers);
}
</script>
<p>{numbers.join(' + ')} = {total}</p>
<button onclick={addNumber}>
Add a number
</button>