Is there a mechanism in Svelte 3 for comparing prop changes inside a component before rendering? Similar to React getDerivedStateFromProps.
<script>
export let color;
// Does anything like this exist in Svelte?
beforeUpdate((changes) => {
const same = changes.prev.color === changes.next.color
})
</script>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With