Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare Prop changes in Svelte 3

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>
like image 968
JeffD23 Avatar asked Nov 11 '19 21:11

JeffD23


2 Answers

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}
like image 106
Bryan Lee Avatar answered Nov 16 '22 09:11

Bryan Lee


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>
like image 38
Tan Li Hau Avatar answered Nov 16 '22 08:11

Tan Li Hau