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

서버에서 불러오기: 로딩·더 불러오기·실패Load from a server: loading, load more, failure

요청하는 동안에는 '불러오는 중' 표시를 보여 주고, 답이 오면 행을 채워 넣어요. 한 번에 한 묶음씩 이어 붙이는 방법, 실패했을 때 기록으로 알리는 방법, 답이 오기 전에 화면이 사라져도 안전한 방법을 보여 줘요.While a request runs it shows a loading text, then fills the rows when the answer arrives. It loads one chunk at a time, reports a failure and stays safe if the screen disappears before the answer.

활용Intermediate
직접 써 보기Live preview서버에서 불러오기: 로딩·더 불러오기·실패Load from a server: loading, load more, failure

코드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="more">더 불러오기</button>
    <button type="button" id="fail">다음 요청 실패시키기</button>
    <button type="button" id="reload">처음부터</button>
  </div>
  <div id="grid" style="height: 440px"></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('more').addEventListener('click', () => actions.more(api));
document.getElementById('fail').addEventListener('click', () => actions.fail(api));
document.getElementById('reload').addEventListener('click', () => actions.reload(api));
example.js
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
export const options = {
  columns: [
    { id: 'orderNo', title: '주문번호', width: 120 },
    { id: 'customer', title: '고객사', width: 180 },
  ],
  rows: [],
  rowKey: 'id',
  loading: true,
};
let say = () => { };
let page = 0;
let busy = false;
let failNext = false;
// 서버에 요청하는 척하는 함수예요. 잠깐 뒤에 한 묶음을 돌려주거나, 실패하게 해 둔 때는 오류를 던져요.
const fetchPage = (index) => new Promise((resolve, reject) => setTimeout(() => {
  if (failNext) {
    failNext = false;
    return reject(new Error('서버가 응답하지 않아요'));
  }
  const first = index * PAGE_SIZE;
  const count = Math.max(0, Math.min(PAGE_SIZE, TOTAL - first));
  resolve(Array.from({ length: count }, (_, i) => ({
    id: first + i + 1,
    orderNo: `SO-${String(first + i + 1).padStart(4, '0')}`,
    customer: customers[(first + i) % customers.length],
  })));
}, 700));
// 실패했을 때 표 바로 위에 이유와 '다시 시도' 버튼을 보여 줘요(기록 창을 보지 않아도 알 수 있게).
let box = null;
let retry = null;
function showError(message) {
  if (!box)
    return;
  box.replaceChildren();
  const text = document.createElement('span');
  text.textContent = message;
  const button = document.createElement('button');
  button.type = 'button';
  button.className = 'btn-x';
  button.textContent = '다시 시도';
  button.addEventListener('click', () => retry?.());
  box.append(text, button);
  box.hidden = false;
}
const hideError = () => {
  if (box)
    box.hidden = true;
};
async function loadNext(api) {
  if (busy)
    return say({ ko: '이미 불러오는 중이에요', en: 'Already loading' });
  if (page * PAGE_SIZE >= TOTAL)
    return say({ ko: '더 불러올 행이 없어요', en: 'No more rows to load' });
  hideError();
  busy = true;
  api.setOptions({ loading: true });
  try {
    const rows = await fetchPage(page);
    if (api.isDestroyed())
      return; // 답이 오기 전에 화면이 사라졌을 수 있어요
    page += 1;
    api.addRows(rows);
    say({
      ko: `${page}번째 묶음: 전체 ${TOTAL}행 중 ${api.getRowCount()}행`,
      en: `Batch ${page}: ${api.getRowCount()} of ${TOTAL} rows`,
    });
  }
  catch (error) {
    if (!api.isDestroyed()) {
      const reason = error instanceof Error ? error.message : '알 수 없는 오류';
      say({ ko: `불러오지 못했어요: ${reason}`, en: `Could not load: ${reason}` });
      showError(`불러오지 못했어요: ${reason}`);
    }
  }
  finally {
    busy = false;
    if (!api.isDestroyed())
      api.setOptions({ loading: false });
  }
}
export function setup(api, log) {
  say = log;
  page = 0;
  busy = false;
  failNext = false;
  box = document.createElement('div');
  box.hidden = true;
  box.style.cssText =
    'display: flex; gap: 8px; align-items: center; margin: 0 0 8px; color: var(--mxg-danger, #b42318); font-size: 13px;';
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', box);
  retry = () => void loadNext(api);
  void loadNext(api);
  return () => {
    say = () => { };
    box?.remove();
    box = null;
    retry = null;
  };
}
export const actions = {
  more: (api) => loadNext(api),
  // '다음 요청 하나를 실패시키기'예요. 이미 불러오는 중이거나 더 불러올 행이 없을 때는 걸어 두지 않아요.
  fail: (api) => {
    if (busy)
      return say({
        ko: '지금은 이미 불러오는 중이라 실패시킬 수 없어요. 끝난 뒤에 눌러 주세요',
        en: 'It is already loading, so it cannot be made to fail now. Press it after it finishes',
      });
    if (page * PAGE_SIZE >= TOTAL)
      return say({
        ko: '더 불러올 행이 없어서 실패시킬 요청이 없어요',
        en: 'No more rows to load, so there is no request to fail',
      });
    failNext = true;
    return loadNext(api);
  },
  reload: (api) => {
    if (busy)
      return say({ ko: '이미 불러오는 중이에요', en: 'Already loading' });
    page = 0;
    failNext = false;
    api.setRows([]);
    return loadNext(api);
  },
};

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="more">Load more</button>
    <button type="button" id="fail">Fail the next request</button>
    <button type="button" id="reload">From the start</button>
  </div>
  <div id="grid" style="height: 440px"></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('more').addEventListener('click', () => actions.more(api));
document.getElementById('fail').addEventListener('click', () => actions.fail(api));
document.getElementById('reload').addEventListener('click', () => actions.reload(api));
example.js
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = [
  'Northwind Logistics',
  'Bluesky Foods',
  'Polaris Trading',
  'Harmony Supply',
  'Dawn Farms',
  'Mode Fashion',
];
export const options = {
  columns: [
    { id: 'orderNo', title: 'Order No.', width: 120 },
    { id: 'customer', title: 'Customer', width: 180 },
  ],
  rows: [],
  rowKey: 'id',
  loading: true,
};
let say = () => { };
let page = 0;
let busy = false;
let failNext = false;
// Pretends to request a batch from a server. After a moment it returns one batch, or throws if a failure was set up.
const fetchPage = (index) => new Promise((resolve, reject) => setTimeout(() => {
  if (failNext) {
    failNext = false;
    return reject(new Error('The server is not responding'));
  }
  const first = index * PAGE_SIZE;
  const count = Math.max(0, Math.min(PAGE_SIZE, TOTAL - first));
  resolve(Array.from({ length: count }, (_, i) => ({
    id: first + i + 1,
    orderNo: `SO-${String(first + i + 1).padStart(4, '0')}`,
    customer: customers[(first + i) % customers.length],
  })));
}, 700));
// On failure, show the reason and a 'Retry' button right above the table (so it is visible without the log).
let box = null;
let retry = null;
function showError(message) {
  if (!box)
    return;
  box.replaceChildren();
  const text = document.createElement('span');
  text.textContent = message;
  const button = document.createElement('button');
  button.type = 'button';
  button.className = 'btn-x';
  button.textContent = 'Retry';
  button.addEventListener('click', () => retry?.());
  box.append(text, button);
  box.hidden = false;
}
const hideError = () => {
  if (box)
    box.hidden = true;
};
async function loadNext(api) {
  if (busy)
    return say('Already loading');
  if (page * PAGE_SIZE >= TOTAL)
    return say('No more rows to load');
  hideError();
  busy = true;
  api.setOptions({ loading: true });
  try {
    const rows = await fetchPage(page);
    if (api.isDestroyed())
      return; // the view may be gone before the answer arrives
    page += 1;
    api.addRows(rows);
    say(`Batch ${page}: ${api.getRowCount()} of ${TOTAL} rows`);
  }
  catch (error) {
    if (!api.isDestroyed()) {
      const reason = error instanceof Error ? error.message : 'Unknown error';
      say(`Could not load: ${reason}`);
      showError(`Could not load: ${reason}`);
    }
  }
  finally {
    busy = false;
    if (!api.isDestroyed())
      api.setOptions({ loading: false });
  }
}
export function setup(api, log) {
  say = log;
  page = 0;
  busy = false;
  failNext = false;
  box = document.createElement('div');
  box.hidden = true;
  box.style.cssText =
    'display: flex; gap: 8px; align-items: center; margin: 0 0 8px; color: var(--mxg-danger, #b42318); font-size: 13px;';
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', box);
  retry = () => void loadNext(api);
  void loadNext(api);
  return () => {
    say = () => { };
    box?.remove();
    box = null;
    retry = null;
  };
}
export const actions = {
  more: (api) => loadNext(api),
  // 'Make the next request fail'. It is not armed while loading or when there are no more rows to load.
  fail: (api) => {
    if (busy)
      return say('It is already loading, so it cannot be made to fail now. Press it after it finishes');
    if (page * PAGE_SIZE >= TOTAL)
      return say('No more rows to load, so there is no request to fail');
    failNext = true;
    return loadNext(api);
  },
  reload: (api) => {
    if (busy)
      return say('Already loading');
    page = 0;
    failNext = false;
    api.setRows([]);
    return loadNext(api);
  },
};