Skip to content

Commit

Permalink
fix(useLabels): deep merge labels
Browse files Browse the repository at this point in the history
  • Loading branch information
MEsteves22 authored and plagoa committed Apr 17, 2024
1 parent deb9129 commit af83d3d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
7 changes: 5 additions & 2 deletions packages/core/src/hooks/useLabels.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { useMemo } from "react";

export function useLabels<T>(defaultLabels: T, labels?: Partial<T>): T {
import { DeepPartial } from "../types/generic";
import { deepMerge } from "../utils/deepMerge";

export function useLabels<T>(defaultLabels: T, labels?: DeepPartial<T>): T {
return useMemo(() => {
return { ...defaultLabels, ...labels };
return deepMerge(defaultLabels, labels);
}, [defaultLabels, labels]);
}
21 changes: 21 additions & 0 deletions packages/core/src/utils/deepMerge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { DeepPartial } from "../types/generic";

const isObject = (val: any): val is Object =>
val && typeof val === "object" && !Array.isArray(val);

function merge<T>(target: T, source?: DeepPartial<T>) {
Object.keys(source || {}).forEach((key) => {
if (isObject(target[key]) && isObject(source?.[key])) {
merge(target[key], source?.[key]);
} else {
target[key] = source?.[key];
}
});
}

/** Merges recursively all keys of source into target returning the resulting object. */
export function deepMerge<T>(target: T, source?: DeepPartial<T>): T {
const result = structuredClone(target);
merge(result, source);
return result;
}

0 comments on commit af83d3d

Please sign in to comment.