Skip to content

Commit

Permalink
fix: 🐛 Fixes fillEmptyValues to include nested arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
aviemet committed Mar 22, 2023
1 parent 21749d9 commit 4089f82
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
15 changes: 8 additions & 7 deletions src/useInertiaForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,14 @@ export default function useInertiaForm<TForm>(
const isMounted = useRef<boolean>()

// Data
const rememberKey = typeof rememberKeyOrInitialValues === 'string' ? rememberKeyOrInitialValues : null
const transformedData = fillEmptyValues(
(typeof rememberKeyOrInitialValues === 'string' ?
maybeInitialValues : rememberKeyOrInitialValues)
|| ({} as TForm),
)
const [defaults, setDefaults] = useState(transformedData)
let rememberKey = null
let transformedData = rememberKeyOrInitialValues
if(typeof rememberKeyOrInitialValues === 'string') {
rememberKey = rememberKeyOrInitialValues
transformedData = maybeInitialValues
}

const [defaults, setDefaults] = useState((fillEmptyValues(transformedData) || {}) as TForm)
const [data, setData] = rememberKey ? useRemember<TForm>(defaults, `${rememberKey}:data`) : useState<TForm>(defaults)

// Errors
Expand Down
17 changes: 10 additions & 7 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,22 @@ export const unsetCompact = (data: NestedObject, path: string) => {
}

export const fillEmptyValues = <TForm>(data: TForm) => {
const sanitizedDefaultData = structuredClone(data)
const clone = structuredClone(data)

for(const key in sanitizedDefaultData) {
if(isPlainObject(sanitizedDefaultData[key])) {
for(const key in clone) {
if(isPlainObject(clone[key])) {
// @ts-ignore
clone[key] = fillEmptyValues(clone[key])
} else if(Array.isArray(clone[key])) {
// @ts-ignore
sanitizedDefaultData[key] = fillEmptyValues(sanitizedDefaultData[key])
} else if(sanitizedDefaultData[key] === undefined || sanitizedDefaultData[key] === null) {
clone[key] = clone[key].map(el => fillEmptyValues(el))
} else if(clone[key] === undefined || clone[key] === null) {
// @ts-ignore
sanitizedDefaultData[key] = ''
clone[key] = ''
}
}

return sanitizedDefaultData
return clone
}

/**
Expand Down

0 comments on commit 4089f82

Please sign in to comment.