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

서버에서 한 페이지씩만 받아 오기Fetch one page at a time from a server

주문 2,000건이 서버에 있어도 화면에는 필요한 10건만 받아 와요. 페이지를 넘기거나 헤더로 정렬하거나 검색·국가를 바꿀 때마다 그리드가 서버에 새 요청을 보내고, 늦게 온 옛 응답은 알아서 버려요.Even with 2,000 orders on a server, the grid fetches only the 10 it shows. Paging, sorting or changing the search triggers a new request, and stale responses are dropped automatically.

심화Advanced
직접 써 보기Live preview서버에서 한 페이지씩만 받아 오기Fetch one page at a time from a server

코드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">
    <input type="text" aria-label="고객사·상품 검색" placeholder="예: 한빛" id="query" />
    <select aria-label="국가" id="country">
      <option value="all" selected>전체</option>
      <option value="kr">한국</option>
      <option value="us">미국</option>
      <option value="jp">일본</option>
      <option value="cn">중국</option>
      <option value="gb">영국</option>
      <option value="fr">프랑스</option>
    </select>
    <button type="button" id="failOnce">다음 요청 한 번 실패시키기</button>
  </div>
  <div id="grid" style="height: 460px"></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('query').addEventListener('input', (event) => actions.query(api, event.target.value));
document.getElementById('country').addEventListener('change', (event) => actions.country(api, event.target.value));
document.getElementById('failOnce').addEventListener('click', () => actions.failOnce(api));
example.js
const customers = [
  '한빛물류',
  '푸른하늘식품',
  '북극성무역',
  '다온상사',
  '새벽농원',
  '모아패션',
  '해든전자',
];
const countries = ['한국', '미국', '일본', '중국', '영국', '프랑스'];
const products = ['무선 이어폰', '스마트 워치', '노트북 거치대', '보조배터리', '블루투스 스피커'];
// 서버에 주문 2,000건이 있다고 가정해요. 이 예제는 서버 대신 메모리에서 0.4초 뒤에 답을 돌려줘요.
const ALL = Array.from({ length: 2000 }, (_, i) => ({
  id: i + 1,
  customer: customers[i % 7],
  country: countries[(i * 5) % 6],
  product: products[(i * 7) % 5],
  amount: 29000 + ((i * 7919) % 480000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// 실제 서비스라면 GET /orders?page=3&size=10&sort=amount,desc&q=… 같은 요청이에요.
// 그리드는 "몇 쪽, 몇 건, 어떤 정렬·필터"인지만 넘기고, 서버는 그 쪽 행과 전체 건수를 돌려줘요.
function fetchPage({ page, pageSize, sort, signal }) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      if (failNext) {
        failNext = false;
        reject(new Error('서버가 응답하지 않아요'));
        return;
      }
      let rows = ALL.filter((r) => (!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
        (state.country === 'all' || r.country === state.country));
      const first = sort[0];
      if (first) {
        const sign = first.direction === 'desc' ? -1 : 1;
        const key = first.columnId;
        rows = [...rows].sort((a, b) => typeof a[key] === 'number'
          ? sign * (a[key] - b[key])
          : sign * String(a[key]).localeCompare(String(b[key]), 'ko'));
      }
      resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
    }, delay);
    // 더 새로운 요청이 오면 그리드가 이전 요청을 취소해요.
    signal.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(new DOMException('aborted', 'AbortError'));
    });
  });
}
export const options = {
  columns: [
    { id: 'customer', title: '고객사', width: 130 },
    { id: 'country', title: '국가', width: 90 },
    { id: 'product', title: '상품', width: 160 },
    {
      id: 'amount',
      title: '금액(원)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: [],
  rowKey: 'id',
  pagination: {
    mode: 'server',
    pageSize: 10,
    pageSizes: [10, 20],
    loadPage: fetchPage,
    jump: true,
  },
};
export function setup(api, log) {
  delay = 400;
  failNext = false;
  state.query = '';
  state.country = 'all';
  const offPage = api.on('pageChanged', ({ page, reason }) => log({
    ko: `${page}페이지를 서버에 요청 (${reason})`,
    en: `Requested page ${page} from the server (${reason})`,
  }));
  const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
    if (error)
      log({
        ko: '불러오기 실패 — 페이지 막대의 "다시 시도"를 눌러 보세요',
        en: 'Load failed — press "Retry" in the pager',
      });
    else if (!loading)
      log({
        ko: `도착: 조건에 맞는 ${api.getPageInfo().totalRows}건`,
        en: `Arrived: ${api.getPageInfo().totalRows} matching rows`,
      });
  });
  return () => {
    offPage();
    offLoad();
  };
}
// 조작 칸의 값은 언어와 상관없는 키라서, 키를 표의 값으로 바꿔 써요.
const COUNTRY_BY_KEY = {
  kr: '한국',
  us: '미국',
  jp: '일본',
  cn: '중국',
  gb: '영국',
  fr: '프랑스',
};
export const actions = {
  query: (api, value) => {
    state.query = (value ?? '').trim();
    api.reloadPage();
  },
  country: (api, value) => {
    state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
    api.reloadPage();
  },
  // 다음 요청 한 번을 일부러 실패시켜요.
  failOnce: (api) => {
    failNext = true;
    api.reloadPage();
  },
};

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">
    <input
      type="text"
      aria-label="Search"
      placeholder="e.g. Wireless"
      id="query"
    />
    <select aria-label="Country" id="country">
      <option value="all" selected>All</option>
      <option value="kr">Korea</option>
      <option value="us">USA</option>
      <option value="jp">Japan</option>
      <option value="cn">China</option>
      <option value="gb">UK</option>
      <option value="fr">France</option>
    </select>
    <button type="button" id="failOnce">Fail the next request</button>
  </div>
  <div id="grid" style="height: 460px"></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('query').addEventListener('input', (event) => actions.query(api, event.target.value));
document.getElementById('country').addEventListener('change', (event) => actions.country(api, event.target.value));
document.getElementById('failOnce').addEventListener('click', () => actions.failOnce(api));
example.js
const customers = [
  'Harbor Logistics',
  'Blue Sky Foods',
  'Polaris Trading',
  'Dawn Commerce',
  'Sunrise Farm',
  'Moda Fashion',
  'Bright Electronics',
];
const countries = ['Korea', 'USA', 'Japan', 'China', 'UK', 'France'];
const products = [
  'Wireless earbuds',
  'Smart watch',
  'Laptop stand',
  'Power bank',
  'Bluetooth speaker',
];
// Pretend the server holds 2,000 orders. Instead of a server, this example answers from memory after 0.4 seconds.
const ALL = Array.from({ length: 2000 }, (_, i) => ({
  id: i + 1,
  customer: customers[i % 7],
  country: countries[(i * 5) % 6],
  product: products[(i * 7) % 5],
  amount: 29 + Math.round(((i * 7919) % 480000) / 1000),
}));
let delay = 400;
let failNext = false;
const state = { query: '', country: 'all' };
// In a real service this is a request like GET /orders?page=3&size=10&sort=amount,desc&q=...
// The grid only passes "which page, how many rows, what sort and filter", and the server returns that page's rows and the total count.
function fetchPage({ page, pageSize, sort, signal }) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      if (failNext) {
        failNext = false;
        reject(new Error('The server is not responding'));
        return;
      }
      let rows = ALL.filter((r) => (!state.query || r.customer.includes(state.query) || r.product.includes(state.query)) &&
        (state.country === 'all' || r.country === state.country));
      const first = sort[0];
      if (first) {
        const sign = first.direction === 'desc' ? -1 : 1;
        const key = first.columnId;
        rows = [...rows].sort((a, b) => typeof a[key] === 'number'
          ? sign * (a[key] - b[key])
          : sign * String(a[key]).localeCompare(String(b[key]), 'en'));
      }
      resolve({ rows: rows.slice((page - 1) * pageSize, page * pageSize), totalRows: rows.length });
    }, delay);
    // When a newer request arrives, the grid cancels the previous one.
    signal.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(new DOMException('aborted', 'AbortError'));
    });
  });
}
export const options = {
  columns: [
    { id: 'customer', title: 'Customer', width: 150 },
    { id: 'country', title: 'Country', width: 100 },
    { id: 'product', title: 'Product', width: 170 },
    {
      id: 'amount',
      title: 'Amount ($)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    },
  ],
  rows: [],
  rowKey: 'id',
  pagination: {
    mode: 'server',
    pageSize: 10,
    pageSizes: [10, 20],
    loadPage: fetchPage,
    jump: true,
  },
};
export function setup(api, log) {
  delay = 400;
  failNext = false;
  state.query = '';
  state.country = 'all';
  const offPage = api.on('pageChanged', ({ page, reason }) => log(`Requested page ${page} from the server (${reason})`));
  const offLoad = api.on('pageLoadChanged', ({ loading, error }) => {
    if (error)
      log('Load failed — press "Retry" in the pager');
    else if (!loading)
      log(`Arrived: ${api.getPageInfo().totalRows} matching rows`);
  });
  return () => {
    offPage();
    offLoad();
  };
}
// The control values are language-neutral keys; map them to the values in the table.
const COUNTRY_BY_KEY = {
  kr: 'Korea',
  us: 'USA',
  jp: 'Japan',
  cn: 'China',
  gb: 'UK',
  fr: 'France',
};
export const actions = {
  query: (api, value) => {
    state.query = (value ?? '').trim();
    api.reloadPage();
  },
  country: (api, value) => {
    state.country = value && value !== 'all' ? (COUNTRY_BY_KEY[value] ?? 'all') : 'all';
    api.reloadPage();
  },
  // Deliberately fail the next request once.
  failOnce: (api) => {
    failNext = true;
    api.reloadPage();
  },
};