Skip to content

Commit

Permalink
PR4814: fix deeply nested replace on row edit
Browse files Browse the repository at this point in the history
  • Loading branch information
bu3alwa committed Aug 27, 2023
1 parent dbaf012 commit eff5831
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 4 deletions.
7 changes: 3 additions & 4 deletions components/lib/datatable/BodyCell.js
Original file line number Diff line number Diff line change
Expand Up @@ -271,15 +271,14 @@ export const BodyCell = React.memo((props) => {
const editorCallback = (val) => {
let editingRowData = { ...editingRowDataState };

editingRowData[field] = val;

ObjectUtils.mutateFieldData(editingRowData, field, val);
setEditingRowDataState(editingRowData);

// update editing meta for complete methods on row mode
const currentData = getEditingRowData();
let currentData = getEditingRowData();

if (currentData) {
currentData[field] = val;
ObjectUtils.mutateFieldData(currentData, field, val);
}
};

Expand Down
51 changes: 51 additions & 0 deletions components/lib/utils/ObjectUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -416,4 +416,55 @@ export default class ObjectUtils {

return [];
}

/**
* This function takes mutates and object with a new value given
* a specific field. This will handle deeply nested fields that
* need to be modified or created.
*
* e.g:
* data = {
* nested: {
* foo: "bar"
* }
* }
*
* field = "nested.foo"
* value = "baz"
*
* The function will mutate data to be
* e.g:
* data = {
* nested: {
* foo: "baz"
* }
* }
*
* @param {object} data the object to be modified
* @param {string} field the field in the object to replace
* @param {any} value the value to have replaced in the field
*/
static mutateFieldData(data, field, value) {
if (typeof data !== 'object' || typeof field !== 'string') {
// short circuit if there is nothing to resolve
return;
}

const fields = field.split('.');
let obj = data;

for (var i = 0, len = fields.length; i < len; ++i) {
// Check if we are on the last field
if (i + 1 - len === 0) {
obj[fields[i]] = value;
break;
}

if (!obj[fields[i]]) {
obj[fields[i]] = {};
}

obj = obj[fields[i]];
}
}
}
1 change: 1 addition & 0 deletions components/lib/utils/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export declare class ObjectUtils {
static equals(obj1: any, obj2: any, field: string): boolean;
static deepEquals(a: any, b: any): boolean;
static resolveFieldData(data: any, field: string): any;
static mutateFieldData(data: object, field: string, value: any): void;
static findDiffKeys(obj1: any, obj2: any): object;
static reorderArray(value: any, from: number, to: number): void;
static findIndexInList(value: any, list: any[], dataKey?: string): number;
Expand Down

0 comments on commit eff5831

Please sign in to comment.