From b3cf1f3f5ac212ffa9dc0cc52a912f8b376f3e82 Mon Sep 17 00:00:00 2001 From: Kevin Fabre Date: Thu, 28 Sep 2023 10:18:20 +0200 Subject: [PATCH] chore: create svelte store to deep compare values Update the store value if previous and new values aren't deep equal --- .../src/components/MapPoi/Map.svelte | 48 ++++--------------- .../src/stores/createDeepEqual.ts | 29 +++++++++++ 2 files changed, 39 insertions(+), 38 deletions(-) create mode 100644 packages/visualizations/src/stores/createDeepEqual.ts diff --git a/packages/visualizations/src/components/MapPoi/Map.svelte b/packages/visualizations/src/components/MapPoi/Map.svelte index e6028b94..b58cf467 100644 --- a/packages/visualizations/src/components/MapPoi/Map.svelte +++ b/packages/visualizations/src/components/MapPoi/Map.svelte @@ -1,5 +1,5 @@
@@ -76,8 +48,8 @@ {sources} {layers} {popupsConfiguration} - {bbox} - {center} + bbox={$bbox} + center={$center} {zoom} {title} {subtitle} diff --git a/packages/visualizations/src/stores/createDeepEqual.ts b/packages/visualizations/src/stores/createDeepEqual.ts new file mode 100644 index 00000000..6d4f1c26 --- /dev/null +++ b/packages/visualizations/src/stores/createDeepEqual.ts @@ -0,0 +1,29 @@ +import { writable, get } from 'svelte/store'; + +/** + * Creates a Svelte writable store that compares values deeply before updating. + * + * @param initialValue - The initial value for the store. + * @returns An object containing the subscribe and set methods. + */ +const createDeepEqual = (initialValue: V | undefined) => { + const value = writable(initialValue); + + return { + /** + * Subscribes to changes in the store's value. + */ + subscribe: value.subscribe, + /** + * Sets the new value for the store if it differs from the current value + * by performing a deep comparison. + */ + set: (newValue: V | undefined) => { + if (JSON.stringify(newValue) !== JSON.stringify(get(value))) { + value.set(newValue); + } + }, + }; +}; + +export default createDeepEqual;