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

서버에서 정렬·필터하기 (오래된 응답 버리기)Sort and filter on the server (drop stale answers)

정렬이나 필터가 바뀔 때마다 서버에 다시 물어보는 구조예요. 응답이 늦게 오는 순서가 뒤바뀌어도 화면이 옛 결과로 돌아가지 않도록, 요청마다 번호를 붙여 가장 최근 번호의 응답만 반영해요.Every sort or filter change asks the server again. To keep a slow old answer from replacing a newer one, each request gets a number and only the latest is applied.

심화Advanced
직접 써 보기Live preview서버에서 정렬·필터하기 (오래된 응답 버리기)Sort and filter on the server (drop stale answers)

코드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">
    <select aria-label="지역" id="region">
      <option value="all" selected>전체 (기본)</option>
      <option value="seoul">서울</option>
      <option value="gyeonggi">경기</option>
      <option value="busan">부산</option>
      <option value="daegu">대구</option>
    </select>
    <button type="button" id="amountDesc">금액 큰 순</button>
    <button type="button" id="amountAsc">금액 작은 순</button>
  </div>
  <div id="grid" style="height: 560px"></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('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('amountDesc').addEventListener('click', () => actions.amountDesc(api));
document.getElementById('amountAsc').addEventListener('click', () => actions.amountAsc(api));
example.js
export const options = {
  columns: [
    { id: 'name', title: '고객', width: 170 },
    { id: 'region', title: '지역', width: 100 },
    {
      id: 'amount',
      title: '금액(천원)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: [],
  rowKey: 'id',
  loading: true,
};
// 서버 대신 정렬·필터해서 처음 14건을 돌려주는 함수예요. 응답은 일부러 늦게 오는데, 큰 순 정렬은 1.2초, 나머지는 0.5초 걸려요.
const REGIONS = ['서울', '경기', '부산', '대구'];
// 지역 선택 목록은 영문 id를 넘겨요. 표에 쓰는 지역 이름으로 바꿔요.
const REGION_BY_ID = {
  seoul: '서울',
  gyeonggi: '경기',
  busan: '부산',
  daegu: '대구',
};
const TABLE = Array.from({ length: 2000 }, (_, i) => ({
  id: i + 1,
  name: `고객 ${i + 1}`,
  region: REGIONS[i % REGIONS.length],
  amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort, filter) {
  const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
  return new Promise((resolve) => setTimeout(() => {
    const region = filter?.items.find((item) => item.columnId === 'region')?.value;
    let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
    const first = sort[0];
    if (first) {
      const key = first.columnId;
      const sign = first.direction === 'asc' ? 1 : -1;
      rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
    }
    resolve(rows.slice(0, 14));
  }, delay));
}
let latest = 0;
// 정렬이나 필터가 바뀔 때마다 서버에 다시 물어요. 느린 옛 응답이 새 응답을 덮어쓰면 안 되니까,
// 요청마다 번호를 붙이고 가장 최근 번호의 응답만 반영해요.
async function load(api, log) {
  const request = ++latest;
  const sort = api.getSortModel();
  const region = api.getFilterModel()?.items[0]?.value;
  log({
    ko: `#${request} 요청: 정렬 ${sort[0] ? `${sort[0].columnId === 'amount' ? '금액' : '고객'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : '없음'}, 지역 ${region ?? '전체'}`,
    en: `#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`,
  });
  api.setOptions({ loading: true });
  const rows = await fakeServer(sort, api.getFilterModel());
  if (api.isDestroyed())
    return;
  if (request !== latest)
    return log({
      ko: `#${request} 응답은 더 새 요청이 있어서 버렸어요`,
      en: `#${request} response dropped because a newer request exists`,
    });
  api.setRows(rows);
  api.setOptions({ loading: false });
  log({ ko: `#${request} 반영: ${rows.length}행`, en: `#${request} applied: ${rows.length} rows` });
}
export function setup(api, log) {
  latest = 0;
  void load(api, log);
  const offs = [
    api.on('sortChanged', () => void load(api, log)),
    api.on('filterChanged', () => void load(api, log)),
  ];
  return () => {
    latest++; // 정리한 뒤에 오는 응답은 버려요
    offs.forEach((off) => off());
  };
}
export const actions = {
  region: (api, value) => api.setFilterModel(value && value !== 'all'
    ? {
      match: 'all',
      items: [
        { columnId: 'region', operator: 'equals', value: REGION_BY_ID[value] ?? value },
      ],
    }
    : null),
  amountDesc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
  amountAsc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};

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">
    <select aria-label="Region" id="region">
      <option value="all" selected>All (default)</option>
      <option value="seoul">New York</option>
      <option value="gyeonggi">Boston</option>
      <option value="busan">Chicago</option>
      <option value="daegu">Austin</option>
    </select>
    <button type="button" id="amountDesc">Amount high to low</button>
    <button type="button" id="amountAsc">Amount low to high</button>
  </div>
  <div id="grid" style="height: 560px"></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('region').addEventListener('change', (event) => actions.region(api, event.target.value));
document.getElementById('amountDesc').addEventListener('click', () => actions.amountDesc(api));
document.getElementById('amountAsc').addEventListener('click', () => actions.amountAsc(api));
example.js
export const options = {
  columns: [
    { id: 'name', title: 'Customer', width: 170 },
    { id: 'region', title: 'Region', width: 110 },
    {
      id: 'amount',
      title: 'Amount ($1,000)',
      kind: 'number',
      width: 150,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    },
  ],
  rows: [],
  rowKey: 'id',
  loading: true,
};
// A function that sorts and filters in place of a server and returns the first 14 rows. The response arrives late on purpose: a descending sort takes 1.2 s, the rest 0.5 s.
const REGIONS = ['New York', 'Boston', 'Chicago', 'Austin'];
// The region select passes ASCII ids, so map them to the region names used in the table.
const REGION_VALUES = {
  seoul: 'New York',
  gyeonggi: 'Boston',
  busan: 'Chicago',
  daegu: 'Austin',
};
const TABLE = Array.from({ length: 2000 }, (_, i) => ({
  id: i + 1,
  name: `Customer ${i + 1}`,
  region: REGIONS[i % REGIONS.length],
  amount: 100 + ((i * 7919) % 9000),
}));
function fakeServer(sort, filter) {
  const delay = sort[0]?.direction === 'desc' ? 1200 : 500;
  return new Promise((resolve) => setTimeout(() => {
    const region = filter?.items.find((item) => item.columnId === 'region')?.value;
    let rows = region ? TABLE.filter((row) => row.region === region) : TABLE.slice();
    const first = sort[0];
    if (first) {
      const key = first.columnId;
      const sign = first.direction === 'asc' ? 1 : -1;
      rows = rows.sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
    }
    resolve(rows.slice(0, 14));
  }, delay));
}
let latest = 0;
// Ask the server again whenever the sort or filter changes. A slow old response must not overwrite a new one,
// so number each request and apply only the response with the latest number.
async function load(api, log) {
  const request = ++latest;
  const sort = api.getSortModel();
  const region = api.getFilterModel()?.items[0]?.value;
  log(`#${request} request: sort ${sort[0] ? `${sort[0].columnId === 'amount' ? 'amount' : 'customer'} ${sort[0].direction === 'asc' ? '▲' : '▼'}` : 'none'}, region ${region ?? 'all'}`);
  api.setOptions({ loading: true });
  const rows = await fakeServer(sort, api.getFilterModel());
  if (api.isDestroyed())
    return;
  if (request !== latest)
    return log(`#${request} response dropped because a newer request exists`);
  api.setRows(rows);
  api.setOptions({ loading: false });
  log(`#${request} applied: ${rows.length} rows`);
}
export function setup(api, log) {
  latest = 0;
  void load(api, log);
  const offs = [
    api.on('sortChanged', () => void load(api, log)),
    api.on('filterChanged', () => void load(api, log)),
  ];
  return () => {
    latest++; // discard responses that arrive after cleanup
    offs.forEach((off) => off());
  };
}
export const actions = {
  region: (api, value) => api.setFilterModel(value && value !== 'all'
    ? {
      match: 'all',
      items: [
        { columnId: 'region', operator: 'equals', value: REGION_VALUES[value] ?? value },
      ],
    }
    : null),
  amountDesc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'desc' }]),
  amountAsc: (api) => api.setSortModel([{ columnId: 'amount', direction: 'asc' }]),
};