Skip to content

Commit

Permalink
feat: handle nested object modification
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulFarault committed Mar 8, 2023
1 parent c0ef7aa commit 85da0b4
Showing 1 changed file with 28 additions and 13 deletions.
41 changes: 28 additions & 13 deletions src/components/Services/VariablesDisplay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,9 @@ function ServiceVariables({ variables }: { variables: Object }) {
let dirtyValues: Object
if (showRawMode) {
const editorValues = JSON.parse(editorRef.current.getValue()) as Object
dirtyValues = Object.keys(editorValues).reduce((acc, key) => {
if (variables.hasOwnProperty(key)) {
if (variables[key] !== editorValues[key]) {
acc[key] = editorValues[key]
}
} else {
acc[key] = editorValues[key]
}
return acc
}, {})
dirtyValues = getDirtyValues(variables, editorValues)
} else {
dirtyValues = getDirtyValues(dirtyFields, getValues)
dirtyValues = getRHFDirtyValues(dirtyFields, getValues)
}
if (currentServiceId && currentComponentId) {
dispatch(
Expand All @@ -99,7 +90,7 @@ function ServiceVariables({ variables }: { variables: Object }) {
if (currentServiceId && !currentComponentId) {
dispatch(setServiceVariables(dirtyValues))
}
reset(merge(variables, dirtyValues))
reset(flattenObject(merge(variables, dirtyValues)))
}

return (
Expand All @@ -114,6 +105,27 @@ function ServiceVariables({ variables }: { variables: Object }) {
)
}

function getDirtyValues(baseObject: Object, object: Object) {
const dirtyValues = {}
Object.keys(object).forEach((key) => {
if (baseObject.hasOwnProperty(key)) {
if (baseObject[key] !== object[key]) {
if (typeof baseObject[key] === 'object') {
const dirtySubValues = getDirtyValues(baseObject[key], object[key])
if (Object.keys(dirtySubValues).length > 0) {
dirtyValues[key] = dirtySubValues
}
} else {
dirtyValues[key] = object[key]
}
}
} else {
dirtyValues[key] = object[key]
}
})
return dirtyValues
}

function VariablesEditionZone({
variables,
saveVariables,
Expand All @@ -139,7 +151,10 @@ function VariablesEditionZone({
)
}

function getDirtyValues(dirtyFields: Object, getValues: (key: string) => any) {
function getRHFDirtyValues(
dirtyFields: Object,
getValues: (key: string) => any
) {
const dirtyValues = {}
Object.keys(dirtyFields).forEach((key) => {
dirtyValues[key] = getValues(key)
Expand Down

0 comments on commit 85da0b4

Please sign in to comment.