-
-
Notifications
You must be signed in to change notification settings - Fork 34
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: passing parent to the onAdd fn #469
Comments
I agree that it would be easier for developers to process it in some cases, but this change would make the API inconsistent. Instead, how about we provide a utility function |
Good idea, additionally I suggest adding a // TODO fix types
function getPathValue<T = object, R = object>(
obj: T,
path: Path,
getter: (obj: T, key: string | number) => unknown = (obj, key) =>
(obj as any)[key],
) {
return path.reduce(
(acc, key) => getter(acc, key) as any,
obj,
) as unknown as R;
} |
ah ye, it would be better to have an optional getter to handle special data types. Then, this getter should also accept cases like return |
This is my draft api design. interface CustomHandler {
is: (value: unknown, path: Path) => boolean
handler: (value: unknown, key: (string | number)) => unknown
}
function defaultHandler (value: unknown, key: (string | number)): unknown {
...
}
export function getPathValue<T = any> (
obj: T,
path: Path,
customHandlers: CustomHandler[] = []
): unknown {
try {
return path.reduce((acc, key, index) => {
if (acc === null || acc === undefined) {
console.error('Invalid path or value encountered at path', path.slice(0, index))
throw new Error('Invalid path or value encountered')
}
for (const handler of customHandlers) {
if (handler.is(acc, key)) {
return handler.handler(acc, key)
}
}
return defaultHandler(acc, key)
}, obj)
} catch (error) {
console.error(error)
return null // or throw error?
}
} |
I will try to work on this tmr. Let me know If you agree with the draft. You can also send a PR if you want 🙏 |
I suggest passing the parent value to the
onAdd
callback, this can reduce the workload of developers parsing the path.If you agree with this proposal, I would be pleased to submit a PR.
Related code
json-viewer/src/components/DataKeyPair.tsx
Lines 255 to 263 in 8d97593
The text was updated successfully, but these errors were encountered: