use deep clone instead of reference copy

- Original code creates a reference copy of `$doc` into `$work` which means that editing values of `$work` changes the values in `$doc`.
- Fix this behaviour by creating a deep clone of `$doc` into `$work`, so underlying values aren't cross-referenced.
This commit is contained in:
Safwan Parkar
2023-08-10 09:47:53 +04:00
parent da004545d2
commit 399ec90108
2 changed files with 29 additions and 15 deletions
+11
View File
@@ -36,3 +36,14 @@ export function deepEqual<T>(obj1: T, obj2: T): boolean {
return true;
}
/**
* Creates a deep clone of the given object. This function uses the JSON methods for cloning,
* so it may not be suitable for objects with functions, symbols, or other non-JSON-safe data.
*
* @param obj the object to be cloned
* @returns a deep clone of the provided object
*/
export function deepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj));
}
@@ -15,6 +15,7 @@
import AttributeItem from '../attributeItem.svelte';
import { symmetricDifference } from '$lib/helpers/array';
import { isRelationship, isRelationshipToMany } from '../attributes/store';
import { deepClone } from '$lib/helpers/object';
const databaseId = $page.params.database;
const collectionId = $page.params.collection;
@@ -22,21 +23,23 @@
const editing = true;
const work = writable(
Object.keys($doc)
.filter((key) => {
return ![
'$id',
'$collection',
'$collectionId',
'$databaseId',
'$createdAt',
'$updatedAt'
].includes(key);
})
.reduce((obj, key) => {
obj[key] = $doc[key];
return obj;
}, {}) as Models.Document
deepClone(
Object.keys($doc)
.filter((key) => {
return ![
'$id',
'$collection',
'$collectionId',
'$databaseId',
'$createdAt',
'$updatedAt'
].includes(key);
})
.reduce((obj, key) => {
obj[key] = $doc[key];
return obj;
}, {}) as Models.Document
)
);
async function updateData() {