How to compare Prop changes in Svelte 3
Asked Answered
B

2

14

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>
Berber answered 11/11, 2019 at 21:58 Comment(0)
M
44

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>
Meerschaum answered 12/11, 2019 at 6:48 Comment(3)
just wondering if setting prevColor can trigger another reactive statement where prevColor is used.Cadaverine
@Cadaverine you mean this svelte.dev/repl/36d1988c4718405c9208cec2f02b6d2a?version=3.16.7 ?Meerschaum
kind of similar..but here was my exact concern..svelte.dev/repl/d4156f465dbe42a597309fb7af0799c0?version=3.16.7 ..with ReactJS, you can't do that in easy way but i can see Svelte handling it correct...AwesomeCadaverine
D
10

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}
Duro answered 5/2, 2021 at 4:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.