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

자식 불러오기 실패와 다시 시도Paged lazy children: failure and retry

쪽을 받다 실패하면 "더 보기" 줄이 오류와 다시 시도 단추를 보여요. 같은 쪽을 다시 요청해요.When a page fails, the "Load more" line shows the error and a retry button, and retrying asks for the same page.

심화Advanced
직접 써 보기Live preview자식 불러오기 실패와 다시 시도Paged lazy children: failure and retry

코드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="fail">다음 쪽 실패</button>
    <button type="button" id="reload">처음부터 다시</button>
  </div>
  <div id="grid" style="height: 300px"></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('fail').addEventListener('click', () => actions.fail(api));
document.getElementById('reload').addEventListener('click', () => actions.reload(api));
example.js
// 맨 위 폴더만 처음에 있고, 폴더를 펼치면 treeChildrenPaging.load가 0쪽만 불러와요. 다음 쪽은 폴더 아래 "더 보기" 줄로 불러와요.
const folders = [
  { id: 'photos', parentId: null, name: '사진', folder: true, size: '' },
  { id: 'logs', parentId: null, name: '기록', folder: true, size: '' },
  { id: 'archive', parentId: null, name: '보관함', folder: true, size: '' },
];
// 서버가 폴더마다 가진 자식 수(실제로는 fetch가 이 자리에 와요).
const TOTALS = { photos: 23, logs: 120, archive: 45 };
const wait = (ms, signal) => new Promise((resolve, reject) => {
  const timer = setTimeout(resolve, ms);
  signal.addEventListener('abort', () => {
    clearTimeout(timer);
    reject(new DOMException('aborted', 'AbortError')); // 접으면 요청을 멈추고, 늦게 온 응답은 그리드가 버려요.
  });
});
let failNext = false;
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 200 },
    { id: 'size', title: '크기', width: 80, align: 'end' },
  ],
  rows: folders,
  rowKey: 'id',
  tree: {
    parentKey: 'parentId',
    column: 'name',
    expandDepth: 0,
    hasChildren: (row) => row.folder,
  },
  treeChildrenPaging: {
    pageSize: 5,
    mode: 'more',
    load: async ({ parentKey, page, pageSize, signal }) => {
      await wait(450, signal);
      if (failNext && page > 0) {
        failNext = false;
        throw new Error('서버가 응답하지 않아요');
      }
      const total = TOTALS[String(parentKey)] ?? 0;
      const from = page * pageSize;
      const count = Math.max(0, Math.min(pageSize, total - from));
      return {
        total,
        rows: Array.from({ length: count }, (_, i) => ({
          id: `${String(parentKey)}-${from + i + 1}`,
          parentId: String(parentKey),
          name: `${String(parentKey)} ${from + i + 1}`,
          folder: false,
          size: `${(from + i + 1) * 12} KB`,
        })),
      };
    },
  },
};
export function setup(api, log) {
  api.on('treeChildrenLoaded', (e) => log({
    ko: `${String(e.parentKey)}: ${e.page + 1}쪽을 받았어요(${e.count}개).`,
    en: `${String(e.parentKey)}: page ${e.page + 1} loaded (${e.count} rows).`,
  }));
  api.on('treeChildrenError', (e) => log({
    ko: `${String(e.parentKey)}: ${e.page + 1}쪽 오류: ${e.message}`,
    en: `${String(e.parentKey)}: page ${e.page + 1} problem: ${e.message}`,
  }));
  log({
    ko: '"다음 쪽 실패" 후 "더 보기"를 누르면 그 쪽이 실패하고, 줄에서 다시 시도할 수 있어요.',
    en: 'Turn on "Fail next page", then press "Load more": that page fails and the line offers a retry.',
  });
}
export const actions = {
  fail: () => void (failNext = true),
  reload: (api) => api.reloadTreeChildren('archive'),
};

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="fail">Fail next page</button>
    <button type="button" id="reload">Reload</button>
  </div>
  <div id="grid" style="height: 300px"></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('fail').addEventListener('click', () => actions.fail(api));
document.getElementById('reload').addEventListener('click', () => actions.reload(api));
example.js
// Only the top folders exist at first. Opening a folder makes treeChildrenPaging.load fetch page 0 only; the next pages come from the "Load more" line under the folder.
const folders = [
  { id: 'photos', parentId: null, name: 'Photos', folder: true, size: '' },
  { id: 'logs', parentId: null, name: 'Logs', folder: true, size: '' },
  { id: 'archive', parentId: null, name: 'Archive', folder: true, size: '' },
];
// How many children the server has per folder (real code would call fetch here).
const TOTALS = { photos: 23, logs: 120, archive: 45 };
const wait = (ms, signal) => new Promise((resolve, reject) => {
  const timer = setTimeout(resolve, ms);
  signal.addEventListener('abort', () => {
    clearTimeout(timer);
    reject(new DOMException('aborted', 'AbortError')); // Collapsing stops the request and the grid drops a late response.
  });
});
let failNext = false;
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 200 },
    { id: 'size', title: 'Size', width: 80, align: 'end' },
  ],
  rows: folders,
  rowKey: 'id',
  tree: {
    parentKey: 'parentId',
    column: 'name',
    expandDepth: 0,
    hasChildren: (row) => row.folder,
  },
  treeChildrenPaging: {
    pageSize: 5,
    mode: 'more',
    load: async ({ parentKey, page, pageSize, signal }) => {
      await wait(450, signal);
      if (failNext && page > 0) {
        failNext = false;
        throw new Error('The server is not responding');
      }
      const total = TOTALS[String(parentKey)] ?? 0;
      const from = page * pageSize;
      const count = Math.max(0, Math.min(pageSize, total - from));
      return {
        total,
        rows: Array.from({ length: count }, (_, i) => ({
          id: `${String(parentKey)}-${from + i + 1}`,
          parentId: String(parentKey),
          name: `${String(parentKey)} ${from + i + 1}`,
          folder: false,
          size: `${(from + i + 1) * 12} KB`,
        })),
      };
    },
  },
};
export function setup(api, log) {
  api.on('treeChildrenLoaded', (e) => log(`${String(e.parentKey)}: page ${e.page + 1} loaded (${e.count} rows).`));
  api.on('treeChildrenError', (e) => log(`${String(e.parentKey)}: page ${e.page + 1} problem: ${e.message}`));
  log('Turn on "Fail next page", then press "Load more": that page fails and the line offers a retry.');
}
export const actions = {
  fail: () => void (failNext = true),
  reload: (api) => api.reloadTreeChildren('archive'),
};