import React, {
useCallback, useEffect, useMemo, useReducer,
} from 'react';
import DataGrid, {
Column, DataGridTypes, Editing, Pager,
} from 'devextreme-react/data-grid';
import { LoadPanel } from 'devextreme-react/load-panel';
import 'whatwg-fetch';
import reducer, { State } from './reducer.ts';
import {
saveChange, loadOrders, setChanges, setEditRowKey,
} from './actions.ts';
const initialState: State = {
data: [],
changes: [],
editRowKey: null,
isLoading: false,
};
const loadPanelPosition = { of: '#gridContainer' };
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const changesText = useMemo(() => JSON.stringify(state.changes.map((change) => ({
type: change.type,
key: change.type !== 'insert' ? change.key : undefined,
data: change.data,
})), null, ' '), [state.changes]);
useEffect(() => {
loadOrders(dispatch);
}, []);
const onSaving = useCallback((e: DataGridTypes.SavingEvent) => {
e.cancel = true;
e.promise = saveChange(dispatch, e.changes[0]);
}, []);
const onChangesChange = useCallback((changes: DataGridTypes.DataChange[]) => {
setChanges(dispatch, changes);
}, []);
const onEditRowKeyChange = 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}
/>
<Pager visible={true} />
<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 React, {
useCallback, useEffect, useMemo, useReducer,
} from 'react';
import DataGrid, { Column, Editing, Pager } 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' };
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const changesText = useMemo(
() =>
JSON.stringify(
state.changes.map((change) => ({
type: change.type,
key: change.type !== 'insert' ? change.key : undefined,
data: change.data,
})),
null,
' ',
),
[state.changes],
);
useEffect(() => {
loadOrders(dispatch);
}, []);
const onSaving = useCallback((e) => {
e.cancel = true;
e.promise = saveChange(dispatch, e.changes[0]);
}, []);
const onChangesChange = useCallback((changes) => {
setChanges(dispatch, changes);
}, []);
const onEditRowKeyChange = 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}
/>
<Pager visible={true} />
<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 React from 'react';
import ReactDOM from 'react-dom';
import App from './App.tsx';
ReactDOM.render(
<App />,
document.getElementById('app'),
);
import React from 'react';
import { sendRequest } from './utils.ts';
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';
type dispatchType = React.Dispatch<{ type: any, payload?: any }>;
export async function loadOrders(dispatch: dispatchType) {
dispatch({ type: FETCH_PENDING });
try {
const { data } = await sendRequest(`${URL}/Orders?skip=700`);
dispatch({
type: FETCH_SUCCESS,
payload: {
data,
},
});
} catch (err) {
dispatch({ type: FETCH_ERROR });
throw err;
}
}
export async function saveChange(dispatch: dispatchType, change: { type: any; data: any; key: any; }) {
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,
},
});
return data;
} catch (err) {
dispatch({ type: SAVING_ERROR });
throw err;
}
} else {
dispatch({ type: SAVING_CANCEL });
return null;
}
}
async function sendChange(url: string, change: { type: any; data: any; key: any; }) {
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:
return null;
}
}
export function setChanges(dispatch: dispatchType, changes) {
dispatch({
type: SET_CHANGES,
payload: changes,
});
}
export function setEditRowKey(dispatch: dispatchType, editRowKey) {
dispatch({
type: SET_EDIT_ROW_KEY,
payload: editRowKey,
});
}
import applyChanges from 'devextreme/data/apply_changes';
import { DataGridTypes } from 'devextreme-react/data-grid';
import {
FETCH_PENDING,
FETCH_SUCCESS,
FETCH_ERROR,
SAVING_PENDING,
SAVING_SUCCESS,
SAVING_ERROR,
SAVING_CANCEL,
SET_CHANGES,
SET_EDIT_ROW_KEY,
} from './actions.ts';
export interface State {
data: any[];
editRowKey: any;
changes: DataGridTypes.DataChange[];
isLoading: boolean;
}
export default function reducer(state: 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: string, method = 'GET', data = {}) {
const params = Object.keys(data)
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
.join('&');
const result = await fetch(url, {
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);
}
const json = await result.json();
throw json.Message;
}
window.exports = window.exports || {};
window.config = {
transpiler: 'ts',
typescriptOptions: {
module: 'system',
emitDecoratorMetadata: true,
experimentalDecorators: true,
jsx: 'react',
},
meta: {
'react': {
'esModule': true,
},
'typescript': {
'exports': 'ts',
},
'devextreme/time_zone_utils.js': {
'esModule': true,
},
'devextreme/localization.js': {
'esModule': true,
},
'devextreme/viz/palette.js': {
'esModule': true,
},
},
paths: {
'npm:': 'https://unpkg.com/',
},
defaultExtension: 'js',
map: {
'ts': 'npm:plugin-typescript@4.2.4/lib/plugin.js',
'typescript': 'npm:typescript@4.2.4/lib/typescript.js',
'react': 'npm:react@17.0.2/umd/react.development.js',
'react-dom': 'npm:react-dom@17.0.2/umd/react-dom.development.js',
'prop-types': 'npm:prop-types@15.8.1/prop-types.js',
'whatwg-fetch': 'npm:whatwg-fetch@2.0.4/fetch.js',
'rrule': 'npm:rrule@2.6.4/dist/es5/rrule.js',
'luxon': 'npm:luxon@1.28.1/build/global/luxon.min.js',
'es6-object-assign': 'npm:es6-object-assign@1.1.0',
'devextreme': 'npm:devextreme@24.1.7/cjs',
'devextreme-react': 'npm:devextreme-react@24.1.7/cjs',
'jszip': 'npm:jszip@3.10.1/dist/jszip.min.js',
'devextreme-quill': 'npm:devextreme-quill@1.7.1/dist/dx-quill.min.js',
'devexpress-diagram': 'npm:devexpress-diagram@2.2.13/dist/dx-diagram.js',
'devexpress-gantt': 'npm:devexpress-gantt@4.1.56/dist/dx-gantt.js',
'@devextreme/runtime': 'npm:@devextreme/runtime@3.0.13',
'inferno': 'npm:inferno@7.4.11/dist/inferno.min.js',
'inferno-compat': 'npm:inferno-compat/dist/inferno-compat.min.js',
'inferno-create-element': 'npm:inferno-create-element@7.4.11/dist/inferno-create-element.min.js',
'inferno-dom': 'npm:inferno-dom/dist/inferno-dom.min.js',
'inferno-hydrate': 'npm:inferno-hydrate@7.4.11/dist/inferno-hydrate.min.js',
'inferno-clone-vnode': 'npm:inferno-clone-vnode/dist/inferno-clone-vnode.min.js',
'inferno-create-class': 'npm:inferno-create-class/dist/inferno-create-class.min.js',
'inferno-extras': 'npm:inferno-extras/dist/inferno-extras.min.js',
'devextreme-cldr-data': 'npm:devextreme-cldr-data@1.0.3',
// 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',
// Prettier
'prettier/standalone': 'npm:prettier@2.8.8/standalone.js',
'prettier/parser-html': 'npm:prettier@2.8.8/parser-html.js',
},
packages: {
'devextreme': {
defaultExtension: 'js',
},
'devextreme-react': {
main: 'index.js',
},
'devextreme/events/utils': {
main: 'index',
},
'devextreme/localization/messages': {
format: 'json',
defaultExtension: 'json',
},
'devextreme/events': {
main: 'index',
},
'es6-object-assign': {
main: './index.js',
defaultExtension: 'js',
},
},
packageConfigPaths: [
'npm:@devextreme/*/package.json',
'npm:@devextreme/runtime@3.0.13/inferno/package.json',
],
babelOptions: {
sourceMaps: false,
stage0: true,
react: true,
},
};
System.config(window.config);
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,
},
});
} 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,
},
});
return data;
} catch (err) {
dispatch({ type: SAVING_ERROR });
throw err;
}
} else {
dispatch({ type: SAVING_CANCEL });
return null;
}
}
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:
return null;
}
}
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 = {}) {
const params = Object.keys(data)
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
.join('&');
const result = await fetch(url, {
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);
}
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 lang="en">
<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=5.0" />
<link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/24.1.7/css/dx.light.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />
<script src="https://unpkg.com/core-js@2.6.12/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.tsx");
</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;
}