How to compare Prop changes in Svelte 3
I've actually written a package that uses Svelte Stores to give you a simple interface to reference as many previous values as you need.
Svelte Previous.
<script>
export let color;
const [currentColor, previousColor] = usePrevious(color);
$: $currentColor = color;
</script>
{$previousColor} to {$currentColor}
If you want to execute a piece of code only when color
changes, you can use the reactive declaration:
<script>
export let color;
$: {
console.log('color changed', color);
// will only get called when the `color` changed.
}
</script>
But if you want to execute that piece of code with both the current value and previous value, you can do the following:
<script>
export let color;
let prevColor;
$: {
console.log('currentColor:', color, 'prevColor:', prevColor);
prevColor = color;
}
</script>