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

서버에서 받아 오는 동안 로딩과 실패 보여 주기Show loading and failure while fetching from a server

서버에서 받은 행, 불러오는 중인지, 실패했는지는 화면이 상태로 들고 있고, 표에는 그 값을 옵션으로 넘겨요. 상태가 바뀌면 표가 알아서 '불러오는 중' 표시와 행을 바꿔요. React, Vue, Angular 탭에는 각 프레임워크의 방식으로 쓴 같은 예제가 들어 있어요.The screen keeps the fetched rows, the loading flag and the failure as state and passes them to the grid as options, so the grid switches the loading text and the rows by itself. The React, Vue and Angular tabs hold the same example written the way each framework does it.

활용Intermediate
직접 써 보기Live preview서버에서 받아 오는 동안 로딩과 실패 보여 주기Show loading and failure while fetching from a server

실행 화면은 JavaScript 버전이에요. 아래 탭의 React·Vue·Angular 코드는 같은 예제를 각 프레임워크로 직접 쓴 코드예요.The preview runs the JavaScript version. The React, Vue, Angular tabs below hold the same example written for each framework.

코드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="reload">다시 불러오기</button>
    <button type="button" id="fail">실패하는 요청 보내기</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('reload').addEventListener('click', () => actions.reload(api));
document.getElementById('fail').addEventListener('click', () => actions.fail(api));
example.js
// 처음에는 행이 없는 표예요. 서버에서 받은 행은 바깥(화면)이 들고 있다가 표에 넘겨 줘요.
export const options = {
  columns: [
    { id: 'orderNo', title: '주문번호', width: 120 },
    { id: 'customer', title: '고객사', width: 150 },
    {
      id: 'amount',
      title: '금액(원)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: [],
  rowKey: 'id',
};
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
/** 서버에 요청하는 척하는 함수예요. 0.7초 뒤에 6행을 주거나, fail이 true면 오류로 끝나요. */
export function fetchRows(fail) {
  return new Promise((resolve, reject) => setTimeout(() => {
    if (fail)
      return reject(new Error('서버가 응답하지 않아요'));
    resolve(customers.map((customer, i) => ({
      id: i + 1,
      orderNo: `SO-${String(2001 + i)}`,
      customer,
      amount: 430000 + i * 187000,
    })));
  }, 700));
}
// 아래는 이 화면(JavaScript 버전)의 동작이에요. 요청하는 동안 로딩 표시를 켜고, 답이 오면 행을 넣어요.
let say = () => { };
let latest = 0;
let box = null;
async function load(api, fail) {
  const request = ++latest; // 더 새 요청이 있으면 옛 응답은 버려요
  api.setOptions({ loading: true });
  if (box)
    box.hidden = true;
  try {
    const rows = await fetchRows(fail);
    if (api.isDestroyed() || request !== latest)
      return;
    api.setRows(rows);
    say({ ko: `${rows.length}행을 받았어요`, en: `Received ${rows.length} rows` });
  }
  catch (error) {
    if (api.isDestroyed() || request !== latest)
      return;
    const reason = error instanceof Error ? error.message : '알 수 없는 오류';
    say({ ko: `불러오지 못했어요: ${reason}`, en: `Could not load: ${reason}` });
    if (box) {
      box.textContent = `불러오지 못했어요: ${reason}`;
      box.hidden = false;
    }
  }
  finally {
    if (!api.isDestroyed() && request === latest)
      api.setOptions({ loading: false });
  }
}
export function setup(api, log) {
  say = log;
  latest = 0;
  box = document.createElement('div');
  box.hidden = true;
  box.style.cssText = 'margin: 0 0 8px; font-size: 13px; color: var(--mxg-danger, #b42318);';
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', box);
  void load(api, false);
  return () => {
    latest++;
    box?.remove();
    box = null;
  };
}
export const actions = {
  reload: (api) => load(api, false),
  fail: (api) => load(api, true),
};

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="reload">Reload</button>
    <button type="button" id="fail">Send a failing request</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('reload').addEventListener('click', () => actions.reload(api));
document.getElementById('fail').addEventListener('click', () => actions.fail(api));
example.js
// It starts as a table with no rows. The rows received from the server are held outside (by the screen) and handed to the table.
export const options = {
  columns: [
    { id: 'orderNo', title: 'Order No.', width: 120 },
    { id: 'customer', title: 'Customer', width: 170 },
    {
      id: 'amount',
      title: 'Amount ($)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => `$${Number(value).toLocaleString('en-US')}`,
    },
  ],
  rows: [],
  rowKey: 'id',
};
const customers = [
  'Northwind Logistics',
  'Bluesky Foods',
  'Polaris Trading',
  'Harmony Supply',
  'Dawn Farms',
  'Mode Fashion',
];
/** Pretends to request rows from a server. After 0.7 seconds it returns 6 rows, or ends with an error if fail is true. */
export function fetchRows(fail) {
  return new Promise((resolve, reject) => setTimeout(() => {
    if (fail)
      return reject(new Error('The server is not responding'));
    resolve(customers.map((customer, i) => ({
      id: i + 1,
      orderNo: `SO-${String(2001 + i)}`,
      customer,
      amount: 430000 + i * 187000,
    })));
  }, 700));
}
// Below is the behavior of this screen (JavaScript version). Turn the loading indicator on while requesting, and put in the rows when the answer arrives.
let say = () => { };
let latest = 0;
let box = null;
async function load(api, fail) {
  const request = ++latest; // if a newer request exists, discard the old response
  api.setOptions({ loading: true });
  if (box)
    box.hidden = true;
  try {
    const rows = await fetchRows(fail);
    if (api.isDestroyed() || request !== latest)
      return;
    api.setRows(rows);
    say(`Received ${rows.length} rows`);
  }
  catch (error) {
    if (api.isDestroyed() || request !== latest)
      return;
    const reason = error instanceof Error ? error.message : 'Unknown error';
    say(`Could not load: ${reason}`);
    if (box) {
      box.textContent = `Could not load: ${reason}`;
      box.hidden = false;
    }
  }
  finally {
    if (!api.isDestroyed() && request === latest)
      api.setOptions({ loading: false });
  }
}
export function setup(api, log) {
  say = log;
  latest = 0;
  box = document.createElement('div');
  box.hidden = true;
  box.style.cssText = 'margin: 0 0 8px; font-size: 13px; color: var(--mxg-danger, #b42318);';
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', box);
  void load(api, false);
  return () => {
    latest++;
    box?.remove();
    box = null;
  };
}
export const actions = {
  reload: (api) => load(api, false),
  fail: (api) => load(api, true),
};