본문으로 건너뛰기Skip to content
예제 첫화면Examples home

저장하려는데 누가 먼저 고쳤을 때When someone saved the same row first

서버가 줄마다 버전을 관리하면, 내가 저장하려는 줄이 그 사이 다른 사람에게 먼저 바뀌었을 때 서버가 거부해요. 거부된 줄은 변경으로 남아서 "내 수정을 최신 판 위에 다시 올리기"나 "서버 값 쓰기" 중에서 고를 수 있어요.If the server tracks a version per row, it rejects a save when someone changed that row first. The rejected row stays as a change and you can re-apply your edit on the latest version or take the server's value.

심화Advanced
직접 써 보기Live preview저장하려는데 누가 먼저 고쳤을 때When someone saved the same row first

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="otherEdits">다른 사람이 먼저 고침</button>
    <button type="button" id="save">저장</button>
    <button type="button" id="keepMine">내 수정 유지</button>
    <button type="button" id="useTheirs">서버 값 쓰기</button>
  </div>
  <div id="grid" style="height: 240px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('otherEdits').addEventListener('click', () => actions.otherEdits(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('keepMine').addEventListener('click', () => actions.keepMine(api));
document.getElementById('useTheirs').addEventListener('click', () => actions.useTheirs(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
// 저장 결과를 사람이 읽는 말로 바꿔요(status는 영어 코드라서 그대로 보여 주지 않아요).
const saveText = (r, en = false) => {
  const words = {
    saved: ['모두 저장했어요', 'All saved'],
    partial: ['일부만 저장했어요', 'Partly saved'],
    failed: ['저장하지 못했어요', 'Could not save'],
    empty: ['저장할 변경이 없어요', 'No changes to save'],
    invalid: ['값이 맞지 않아 저장하지 않았어요', 'Not saved because a value is not valid'],
    stale: [
      '서버에 더 새로운 값이 있어서 저장하지 못했어요',
      'Could not save because the server has a newer value',
    ],
  };
  const word = words[r.status] ?? ['저장을 마쳤어요', 'Save finished'];
  const counts = r.committed || r.failed
    ? en
      ? ` (${r.committed} succeeded, ${r.failed} failed)`
      : ` (성공 ${r.committed}줄, 실패 ${r.failed}줄)`
    : '';
  return `${word[en ? 1 : 0]}${counts}`;
};
// 가짜 서버는 줄마다 "버전"을 들고 있어요. 저장하려는 줄의 버전이 서버와 같을 때만 받아 주고, 받으면 버전을 1 올려서 돌려줘요.
// 버전이 다르면 "누가 먼저 고쳤다"는 뜻이라서 그 줄을 실패로 돌려줘요.
const server = new Map([
  [1, { id: 1, name: '참나무 테이블', price: 320, version: 1 }],
  [2, { id: 2, name: '소나무 선반', price: 90, version: 1 }],
  [3, { id: 3, name: '자작나무 의자', price: 45, version: 1 }],
]);
const handler = async (changes) => {
  await new Promise((resolve) => setTimeout(resolve, 250));
  const ok = [];
  const failed = [];
  for (const change of changes) {
    const id = Number(change.key);
    const stored = server.get(id);
    if (!stored || stored.version !== change.row.version) {
      failed.push({
        key: id,
        message: L(`서버는 ${stored?.version ?? '?'}판인데 내 줄은 ${change.row.version}판이에요. 누군가 먼저 고쳤어요.`, `The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`),
      });
      continue;
    }
    const next = { ...change.row, version: stored.version + 1 };
    server.set(id, next);
    ok.push({ key: id, row: next });
  }
  return { ok, failed };
};
export const options = {
  columns: [
    { id: 'name', title: '상품', width: 150, editable: true },
    { id: 'price', title: '가격(만원)', kind: 'number', width: 110, align: 'end', editable: true },
    { id: 'version', title: '판', kind: 'number', width: 70, align: 'end' },
  ],
  rows: [...server.values()].map((row) => ({ ...row })),
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: handler,
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log({
    ko: '2번 줄 가격을 고치고, "다른 사람이 먼저 고침"을 누른 뒤 "저장"을 눌러 보세요.',
    en: 'Edit the price of row 2, press "Someone else edited first", then press "Save".',
  });
  const offs = [
    api.on('changesCommitted', ({ changes }) => log({ ko: `✓ ${changes.length}줄 저장했어요`, en: `✓ Saved ${changes.length} rows` })),
    api.on('saveFailed', ({ failed }) => log({
      ko: `✗ ${failed.map((f) => `${f.key}번 줄: ${f.message}`).join(' / ')}`,
      en: `✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`,
    })),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  // 다른 사람이 2번 줄을 먼저 고쳤다고 가정해요(서버의 가격과 판이 올라가요).
  otherEdits: () => {
    const stored = server.get(2);
    if (!stored)
      return;
    server.set(2, { ...stored, price: stored.price + 5, version: stored.version + 1 });
    say({
      ko: `서버의 2번 줄이 바뀌었어요: 가격 ${stored.price + 5}, ${stored.version + 1}판`,
      en: `Row 2 on the server changed: price ${stored.price + 5}, version ${stored.version + 1}`,
    });
  },
  save: async (api) => {
    const report = await api.save();
    say({ ko: `저장 결과: ${saveText(report)}`, en: `Save result: ${saveText(report, true)}` });
  },
  // 출구 1) 내 수정 유지: 같은 수정을 서버의 최신 판 위에 다시 올려 저장해요.
  keepMine: async (api) => {
    const mine = api
      .getChanges()
      .filter((c) => c.state === 'modified')
      .map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
    if (!mine.length)
      return say({ ko: '다시 올릴 수정이 없어요.', en: 'No edit to upload again.' });
    api.updateRows(mine);
    const report = await api.save();
    say({
      ko: `내 수정을 최신 판 위에 다시 올렸어요 — ${saveText(report)}`,
      en: `Put my edit on top of the latest version — ${saveText(report, true)}`,
    });
  },
  // 출구 2) 서버 것 쓰기: 내 수정을 버리고 서버의 줄로 바꾼 뒤 그것을 새 기준으로 삼아요.
  useTheirs: (api) => {
    const keys = api.getChanges().map((c) => Number(c.key));
    api.rollbackChanges();
    const theirs = keys.flatMap((key) => {
      const row = server.get(key);
      return row ? [{ ...row }] : [];
    });
    if (theirs.length)
      api.updateRows(theirs);
    api.commitChanges();
    say({
      ko: '내 수정을 버리고 서버 값으로 바꿨어요.',
      en: 'Discarded my edit and replaced it with the server value.',
    });
  },
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="otherEdits">Someone else edited first</button>
    <button type="button" id="save">Save</button>
    <button type="button" id="keepMine">Keep my edit</button>
    <button type="button" id="useTheirs">Use server value</button>
  </div>
  <div id="grid" style="height: 240px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('otherEdits').addEventListener('click', () => actions.otherEdits(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('keepMine').addEventListener('click', () => actions.keepMine(api));
document.getElementById('useTheirs').addEventListener('click', () => actions.useTheirs(api));
example.js
// Turns the save result into human-readable text (status is an English code, so it is not shown as is).
const saveText = (r) => {
  const words = {
    saved: 'All saved',
    partial: 'Partly saved',
    failed: 'Could not save',
    empty: 'No changes to save',
    invalid: 'Not saved because a value is not valid',
    stale: 'Could not save because the server has a newer value',
  };
  const word = words[r.status] ?? 'Save finished';
  const counts = r.committed || r.failed ? ` (${r.committed} succeeded, ${r.failed} failed)` : '';
  return `${word}${counts}`;
};
// The fake server keeps a "version" per row. It accepts a row only when its version matches the server's, and returns it with the version raised by 1.
// A different version means "someone edited it first", so that row is returned as failed.
const server = new Map([
  [1, { id: 1, name: 'Oak table', price: 3200, version: 1 }],
  [2, { id: 2, name: 'Pine shelf', price: 900, version: 1 }],
  [3, { id: 3, name: 'Birch chair', price: 450, version: 1 }],
]);
const handler = async (changes) => {
  await new Promise((resolve) => setTimeout(resolve, 250));
  const ok = [];
  const failed = [];
  for (const change of changes) {
    const id = Number(change.key);
    const stored = server.get(id);
    if (!stored || stored.version !== change.row.version) {
      failed.push({
        key: id,
        message: `The server has version ${stored?.version ?? '?'} but my row is version ${change.row.version}. Someone edited it first.`,
      });
      continue;
    }
    const next = { ...change.row, version: stored.version + 1 };
    server.set(id, next);
    ok.push({ key: id, row: next });
  }
  return { ok, failed };
};
export const options = {
  columns: [
    { id: 'name', title: 'Product', width: 150, editable: true },
    { id: 'price', title: 'Price ($)', kind: 'number', width: 110, align: 'end', editable: true },
    { id: 'version', title: 'Version', kind: 'number', width: 90, align: 'end' },
  ],
  rows: [...server.values()].map((row) => ({ ...row })),
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: handler,
};
let say = () => { };
export function setup(api, log) {
  say = log;
  log('Edit the price of row 2, press "Someone else edited first", then press "Save".');
  const offs = [
    api.on('changesCommitted', ({ changes }) => log(`✓ Saved ${changes.length} rows`)),
    api.on('saveFailed', ({ failed }) => log(`✗ ${failed.map((f) => `row ${f.key}: ${f.message}`).join(' / ')}`)),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  // Pretend someone else edited row 2 first (the server's price and version go up).
  otherEdits: () => {
    const stored = server.get(2);
    if (!stored)
      return;
    server.set(2, { ...stored, price: stored.price + 50, version: stored.version + 1 });
    say(`Row 2 on the server changed: price ${stored.price + 50}, version ${stored.version + 1}`);
  },
  save: async (api) => {
    const report = await api.save();
    say(`Save result: ${saveText(report)}`);
  },
  // Way out 1) Keep mine: put the same edit on top of the server's latest version and save.
  keepMine: async (api) => {
    const mine = api
      .getChanges()
      .filter((c) => c.state === 'modified')
      .map((c) => ({ ...c.row, version: server.get(Number(c.key))?.version ?? c.row.version }));
    if (!mine.length)
      return say('No edit to upload again.');
    api.updateRows(mine);
    const report = await api.save();
    say(`Put my edit on top of the latest version — ${saveText(report)}`);
  },
  // Way out 2) Use the server's: discard my edit, switch to the server's row and take that as the new baseline.
  useTheirs: (api) => {
    const keys = api.getChanges().map((c) => Number(c.key));
    api.rollbackChanges();
    const theirs = keys.flatMap((key) => {
      const row = server.get(key);
      return row ? [{ ...row }] : [];
    });
    if (theirs.length)
      api.updateRows(theirs);
    api.commitChanges();
    say('Discarded my edit and replaced it with the server value.');
  },
};