Skip to content

Commit

Permalink
[DataGrid] getValueError in valueGetter if incorrect field is supplied (
Browse files Browse the repository at this point in the history
  • Loading branch information
ZeeshanTamboli authored Dec 21, 2020
1 parent 1e51d51 commit ead6bb0
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
18 changes: 17 additions & 1 deletion packages/grid/_modules_/grid/utils/paramsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { GridApi } from '../models/api/gridApi';
import { CellParams } from '../models/params/cellParams';
import { RowParams } from '../models/params/rowParams';

let warnedOnce = false;

export function buildCellParams({
element,
value,
Expand All @@ -27,9 +29,23 @@ export function buildCellParams({
getValue: (field: string) => {
// We are getting the value of another column here, field
const col = api.getColumnFromField(field);
if (!col.valueGetter) {

if (process.env.NODE_ENV !== 'production') {
if (!col && !warnedOnce) {
console.warn(
[
`Material-UI: You are calling getValue('${field}') but the column \`${field}\` is not defined.`,
`Instead, you can access the data from \`params.row.${field}\`.`,
].join('\n'),
);
warnedOnce = true;
}
}

if (!col || !col.valueGetter) {
return rowModel[field];
}

return col.valueGetter(
buildCellParams({
value: rowModel[field],
Expand Down
25 changes: 24 additions & 1 deletion packages/grid/data-grid/src/tests/layout.DataGrid.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from 'test/utils';
import { useFakeTimers } from 'sinon';
import { expect } from 'chai';
import { DataGrid } from '@material-ui/data-grid';
import { DataGrid, ValueGetterParams } from '@material-ui/data-grid';
import { getColumnValues, raf } from 'test/utils/helperFn';

describe('<DataGrid /> - Layout & Warnings', () => {
Expand Down Expand Up @@ -162,6 +162,29 @@ describe('<DataGrid /> - Layout & Warnings', () => {
'Material-UI: useResizeContainer - The parent of the grid has an empty width.',
);
});

it('should warn when CellParams.valueGetter is called with a missing column', () => {
const rows = [
{ id: 1, age: 1 },
{ id: 2, age: 2 },
];
const columns = [
{ field: 'id', hide: true },
{
field: 'fullName',
valueGetter: (params: ValueGetterParams) => params.getValue('age'),
},
];
expect(() => {
render(
<div style={{ width: 300, height: 300 }}>
<DataGrid rows={rows} columns={columns} />
</div>,
);
// @ts-expect-error need to migrate helpers to TypeScript
}).toWarnDev(["You are calling getValue('age') but the column `age` is not defined"]);
expect(getColumnValues()).to.deep.equal(['1', '2']);
});
});

describe('column width', () => {
Expand Down

0 comments on commit ead6bb0

Please sign in to comment.