Your search did not match any results.
Data Grid

Edit State Management (CTP)

Our DataGrid widget manages its edit state automatically. If your use case requires full control over the editing process, you can use the API members below to manage state manually. In this demo, we manage state with a help of the useReducer React hook.

Widget Options

  • editing.editRowKey
    The key for the row being edited.

  • editing.editColumnName
    The name or data field of the column being edited.

  • editing.changes
    Pending row changes.

Bind these options to state props and set the props to change edit state at runtime. In this demo, we bind the editRowKey and changes options and use the corresponding on_OptionName_Change event handlers to set the bound props.

Utility Method

Event Handlers

  • onSaving / onSaved
    Functions that are called before / after pending row changes are saved via the UI or programmatically.

  • onEditCanceling / onEditCanceled
    Functions that are called before / after editing is canceled and pending row changes are discarded.

Use these functions to perform custom actions. In this demo, the onSaving function sends pending changes to a server. The function's parameter e contains fields for this capability. To implement the same in your application, follow these steps:

  1. Disable built-in edit state management
    Set the e.cancel field to true.

  2. Send a request to the server
    Pending changes are stored in the e.changes array. This array has only a single element in all edit modes, except for batch. Check if this element is not empty and send it to the server (see the saveChange action in actions.js).

  3. Apply the same changes to the widget's data source and reset edit state
    If the server successfully saves changes, call the applyChanges method to save the same changes in the widget's data source. Assign null to the editRowKey and an empty array to the changes option. This resets edit state (see the SAVING_SUCCESS handler in reducer.js).

NOTE

This functionality is available as a community technology preview (CTP). Should you have any questions or suggestions prior to its official release, please email your comments to support@devexpress.com.

Copy to CodeSandBox
Apply
Reset
import React from 'react'; import DataGrid, { Column, Editing } from 'devextreme-react/data-grid'; import { LoadPanel } from 'devextreme-react/load-panel'; import 'whatwg-fetch'; import reducer from './reducer.js'; import { saveChange, loadOrders, setChanges, setEditRowKey } from './actions.js'; const initialState = { data: [], changes: [], editRowKey: null, isLoading: false }; const loadPanelPosition = { of: '#gridContainer' }; function App() { const [state, dispatch] = React.useReducer(reducer, initialState); const changesText = React.useMemo(() => { return JSON.stringify(state.changes.map((change) => ({ type: change.type, key: change.type !== 'insert' ? change.key : undefined, data: change.data })), null, ' '); }, [state.changes]); React.useEffect(() => { loadOrders(dispatch); }, []); const onSaving = React.useCallback((e) => { e.cancel = true; e.promise = saveChange(dispatch, e.changes[0]); }, []); const onChangesChange = React.useCallback((changes) => { setChanges(dispatch, changes); }, []); const onEditRowKeyChange = React.useCallback((editRowKey) => { setEditRowKey(dispatch, editRowKey); }, []); return ( <React.Fragment> <LoadPanel position={loadPanelPosition} visible={state.isLoading} /> <DataGrid id="gridContainer" keyExpr="OrderID" dataSource={state.data} showBorders repaintChangesOnly onSaving={onSaving}> <Editing mode="row" allowAdding allowDeleting allowUpdating changes={state.changes} onChangesChange={onChangesChange} editRowKey={state.editRowKey} onEditRowKeyChange={onEditRowKeyChange} /> <Column dataField="OrderID" allowEditing={false}></Column> <Column dataField="ShipName"></Column> <Column dataField="ShipCountry"></Column> <Column dataField="ShipCity"></Column> <Column dataField="ShipAddress"></Column> <Column dataField="OrderDate" dataType="date"></Column> <Column dataField="Freight"></Column> </DataGrid> <div className="options"> <div className="caption">Options</div> <div className="option"> <span>Edit Row Key:</span> <div id="editRowKey">{state.editRowKey === null ? 'null' : state.editRowKey.toString()}</div> </div> <div className="option"> <span>Changes:</span> <div id="changes">{changesText}</div> </div> </div> </React.Fragment> ); } export default App;
import { sendRequest } from './utils.js'; const URL = 'https://js.devexpress.com/Demos/Mvc/api/DataGridWebApi'; export const FETCH_PENDING = 'FETCH_PENDING'; export const FETCH_SUCCESS = 'FETCH_SUCCESS'; export const FETCH_ERROR = 'FETCH_ERROR'; export const SAVING_PENDING = 'SAVING_PENDING'; export const SAVING_SUCCESS = 'SAVING_SUCCESS'; export const SAVING_ERROR = 'SAVING_ERROR'; export const SAVING_CANCEL = 'SAVING_CANCEL'; export const SET_CHANGES = 'SET_CHANGES'; export const SET_EDIT_ROW_KEY = 'SET_EDIT_ROW_KEY'; export async function loadOrders(dispatch) { dispatch({ type: FETCH_PENDING }); try { const { data } = await sendRequest(`${URL}/Orders?skip=700`); dispatch({ type: FETCH_SUCCESS, payload: { data: data } }); } catch(err) { dispatch({ type: FETCH_ERROR }); throw err; } } export async function saveChange(dispatch, change) { if (change && change.type) { let data; dispatch({ type: SAVING_PENDING }); try { data = await sendChange(URL, change); change.data = data; dispatch({ type: SAVING_SUCCESS, payload: { change: change } }); return data; } catch(err) { dispatch({ type: SAVING_ERROR }); throw err; } } else { dispatch({ type: SAVING_CANCEL }); } } async function sendChange(url, change) { switch (change.type) { case 'insert': return sendRequest(`${url}/InsertOrder`, 'POST', { values: JSON.stringify(change.data) }); case 'update': return sendRequest(`${url}/UpdateOrder`, 'PUT', { key: change.key, values: JSON.stringify(change.data) }); case 'remove': return sendRequest(`${url}/DeleteOrder`, 'DELETE', { key: change.key }); default: break; } } export function setChanges(dispatch, changes) { dispatch({ type: SET_CHANGES, payload: changes }); } export function setEditRowKey(dispatch, editRowKey) { dispatch({ type: SET_EDIT_ROW_KEY, payload: editRowKey }); }
import applyChanges from 'devextreme/data/apply_changes'; import { FETCH_PENDING, FETCH_SUCCESS, FETCH_ERROR, SAVING_PENDING, SAVING_SUCCESS, SAVING_ERROR, SAVING_CANCEL, SET_CHANGES, SET_EDIT_ROW_KEY } from './actions.js'; export default function reducer(state, { type, payload }) { let newData; switch (type) { case SAVING_SUCCESS: newData = applyChanges(state.data, [payload.change], { keyExpr: 'OrderID' }); return { ...state, data: newData, changes: [], editRowKey: null, isLoading: false }; case SAVING_CANCEL: return { ...state, changes: [], editRowKey: null }; case SET_CHANGES: return { ...state, changes: payload }; case SET_EDIT_ROW_KEY: return { ...state, editRowKey: payload }; case FETCH_SUCCESS: return { ...state, ...payload, isLoading: false }; case FETCH_PENDING: case SAVING_PENDING: return { ...state, isLoading: true }; case FETCH_ERROR: case SAVING_ERROR: return { ...state, isLoading: false }; default: return state; } }
export async function sendRequest(url, method = 'GET', data) { data = data || {}; const params = Object.keys(data) .map((key) => { return `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`; }) .join('&'); const result = await fetch(url, { method: method, body: params || null, headers: method === 'GET' ? {} : { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, credentials: 'include' }); if (result.ok) { const text = await result.text(); return text && JSON.parse(text); } else { const json = await result.json(); throw json.Message; } }
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.js'; ReactDOM.render( <App />, document.getElementById('app') );
<!DOCTYPE html> <html> <head> <title>DevExtreme Demo</title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> <link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/20.2.4/css/dx.common.css" /> <link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/20.2.4/css/dx.light.css" /> <link rel="stylesheet" type="text/css" href="styles.css" /> <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script> <script src="https://unpkg.com/systemjs@0.21.3/dist/system.js"></script> <script type="text/javascript" src="config.js"></script> <script type="text/javascript"> System.import('./index.js'); </script> </head> <body class="dx-viewport"> <div class="demo-container"> <div id="app"></div> </div> </body> </html>
#gridContainer { height: 440px; } .options { padding: 20px; margin-top: 20px; background-color: rgba(191, 191, 191, 0.15); } .caption { margin-bottom: 10px; font-weight: 500; font-size: 18px; } .option { margin-bottom: 10px; } .option > span { position: relative; margin-right: 14px; } .option > div { display: inline-block; font-weight: bold; }
System.config({ transpiler: 'plugin-babel', meta: { }, paths: { 'npm:': 'https://unpkg.com/' }, defaultExtension: 'js', map: { 'react': 'npm:react@16.14.0/umd/react.development.js', 'react-dom': 'npm:react-dom@16.14.0/umd/react-dom.development.js', 'prop-types': 'npm:prop-types@15.7.2/prop-types.js', 'whatwg-fetch': 'npm:whatwg-fetch@2.0.4/fetch.js', 'rrule': 'npm:rrule@2.6.6/dist/es5/rrule.js', 'luxon': 'npm:luxon@1.25.0/build/global/luxon.min.js', 'es6-object-assign': 'npm:es6-object-assign@1.1.0', 'devextreme': 'npm:devextreme@20.2.4', 'devextreme-react': 'npm:devextreme-react@20.2.4', 'jszip': 'npm:jszip@3.5.0/dist/jszip.min.js', 'devextreme-quill': 'npm:devextreme-quill@0.9.7/dist/dx-quill.min.js', 'devexpress-diagram': 'npm:devexpress-diagram@2.0.5/dist/dx-diagram.js', 'devexpress-gantt': 'npm:devexpress-gantt@2.0.8/dist/dx-gantt.js', 'preact': 'npm:preact@10.5.7/dist/preact.js', 'preact/hooks': 'npm:preact@10.5.7/hooks/dist/hooks.js', // SystemJS plugins 'plugin-babel': 'npm:systemjs-plugin-babel@0.0.25/plugin-babel.js', 'systemjs-babel-build': 'npm:systemjs-plugin-babel@0.0.25/systemjs-babel-browser.js' }, packages: { 'devextreme': { defaultExtension: 'js' }, 'devextreme-react': { main: 'index.js' }, 'devextreme/events/utils': { main: 'index' }, 'devextreme/events': { main: 'index' }, 'es6-object-assign': { main: './index.js', defaultExtension: 'js' } }, babelOptions: { sourceMaps: false, stage0: true, react: true } });