서버에서 불러오기: 로딩·더 불러오기·실패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.
코드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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));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);
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>서버에서 불러오기: 로딩·더 불러오기·실패</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
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 });
}
}
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;
};
}
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);
},
};
options.ariaLabel = "서버에서 불러오기: 로딩·더 불러오기·실패";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('more').addEventListener('click', () => actions.more(api));
document.getElementById('fail').addEventListener('click', () => actions.fail(api));
document.getElementById('reload').addEventListener('click', () => actions.reload(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.more(api)}
>더 불러오기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.fail(api)}
>다음 요청 실패시키기</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reload(api)}
>처음부터</button>
</div>
<Grid style={{ height: 440 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
orderNo: string;
customer: string;
}
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 120 },
{ id: 'customer', title: '고객사', width: 180 },
],
rows: [],
rowKey: 'id',
loading: true,
};
let say: (message: LogText) => void = () => {};
let page = 0;
let busy = false;
let failNext = false;
// 서버에 요청하는 척하는 함수예요. 잠깐 뒤에 한 묶음을 돌려주거나, 실패하게 해 둔 때는 오류를 던져요.
const fetchPage = (index: number): Promise<Row[]> =>
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] as string,
})),
);
}, 700),
);
// 실패했을 때 표 바로 위에 이유와 '다시 시도' 버튼을 보여 줘요(기록 창을 보지 않아도 알 수 있게).
let box: HTMLElement | null = null;
let retry: (() => void) | null = null;
function showError(message: string): void {
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 = (): void => {
if (box) box.hidden = true;
};
async function loadNext(api: GridApi<Row>): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => loadNext(api),
// '다음 요청 하나를 실패시키기'예요. 이미 불러오는 중이거나 더 불러올 행이 없을 때는 걸어 두지 않아요.
fail: (api: GridApi<Row>) => {
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: GridApi<Row>) => {
if (busy) return say({ ko: '이미 불러오는 중이에요', en: 'Already loading' });
page = 0;
failNext = false;
api.setRows([]);
return loadNext(api);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.more(api)">더 불러오기</button>
<button type="button" :disabled="!api" @click="api && actions.fail(api)">다음 요청 실패시키기</button>
<button type="button" :disabled="!api" @click="api && actions.reload(api)">처음부터</button>
</div>
<Grid style="height: 440px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
orderNo: string;
customer: string;
}
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 120 },
{ id: 'customer', title: '고객사', width: 180 },
],
rows: [],
rowKey: 'id',
loading: true,
};
let say: (message: LogText) => void = () => {};
let page = 0;
let busy = false;
let failNext = false;
// 서버에 요청하는 척하는 함수예요. 잠깐 뒤에 한 묶음을 돌려주거나, 실패하게 해 둔 때는 오류를 던져요.
const fetchPage = (index: number): Promise<Row[]> =>
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] as string,
})),
);
}, 700),
);
// 실패했을 때 표 바로 위에 이유와 '다시 시도' 버튼을 보여 줘요(기록 창을 보지 않아도 알 수 있게).
let box: HTMLElement | null = null;
let retry: (() => void) | null = null;
function showError(message: string): void {
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 = (): void => {
if (box) box.hidden = true;
};
async function loadNext(api: GridApi<Row>): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => loadNext(api),
// '다음 요청 하나를 실패시키기'예요. 이미 불러오는 중이거나 더 불러올 행이 없을 때는 걸어 두지 않아요.
fail: (api: GridApi<Row>) => {
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: GridApi<Row>) => {
if (busy) return say({ ko: '이미 불러오는 중이에요', en: 'Already loading' });
page = 0;
failNext = false;
api.setRows([]);
return loadNext(api);
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.more(api)"
>더 불러오기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.fail(api)"
>다음 요청 실패시키기</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reload(api)"
>처음부터</button>
</div>
<mx-grid style="height: 440px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
orderNo: string;
customer: string;
}
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = ['한빛물류', '푸른하늘식품', '북극성무역', '다온상사', '새벽농원', '모아패션'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: '주문번호', width: 120 },
{ id: 'customer', title: '고객사', width: 180 },
],
rows: [],
rowKey: 'id',
loading: true,
};
let say: (message: LogText) => void = () => {};
let page = 0;
let busy = false;
let failNext = false;
// 서버에 요청하는 척하는 함수예요. 잠깐 뒤에 한 묶음을 돌려주거나, 실패하게 해 둔 때는 오류를 던져요.
const fetchPage = (index: number): Promise<Row[]> =>
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] as string,
})),
);
}, 700),
);
// 실패했을 때 표 바로 위에 이유와 '다시 시도' 버튼을 보여 줘요(기록 창을 보지 않아도 알 수 있게).
let box: HTMLElement | null = null;
let retry: (() => void) | null = null;
function showError(message: string): void {
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 = (): void => {
if (box) box.hidden = true;
};
async function loadNext(api: GridApi<Row>): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => loadNext(api),
// '다음 요청 하나를 실패시키기'예요. 이미 불러오는 중이거나 더 불러올 행이 없을 때는 걸어 두지 않아요.
fail: (api: GridApi<Row>) => {
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: GridApi<Row>) => {
if (busy) return say({ ko: '이미 불러오는 중이에요', en: 'Already loading' });
page = 0;
failNext = false;
api.setRows([]);
return loadNext(api);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<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>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));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);
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Load from a server: loading, load more, failure</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harmony Supply',
'Dawn Farms',
'Mode Fashion',
];
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 });
}
}
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;
};
}
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);
},
};
options.ariaLabel = "Load from a server: loading, load more, failure";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('more').addEventListener('click', () => actions.more(api));
document.getElementById('fail').addEventListener('click', () => actions.fail(api));
document.getElementById('reload').addEventListener('click', () => actions.reload(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.more(api)}
>Load more</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.fail(api)}
>Fail the next request</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.reload(api)}
>From the start</button>
</div>
<Grid style={{ height: 440 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
orderNo: string;
customer: string;
}
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harmony Supply',
'Dawn Farms',
'Mode Fashion',
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: 'Order No.', width: 120 },
{ id: 'customer', title: 'Customer', width: 180 },
],
rows: [],
rowKey: 'id',
loading: true,
};
let say: (message: LogText) => void = () => {};
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: number): Promise<Row[]> =>
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] as string,
})),
);
}, 700),
);
// On failure, show the reason and a 'Retry' button right above the table (so it is visible without the log).
let box: HTMLElement | null = null;
let retry: (() => void) | null = null;
function showError(message: string): void {
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 = (): void => {
if (box) box.hidden = true;
};
async function loadNext(api: GridApi<Row>): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => loadNext(api),
// 'Make the next request fail'. It is not armed while loading or when there are no more rows to load.
fail: (api: GridApi<Row>) => {
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: GridApi<Row>) => {
if (busy) return say('Already loading');
page = 0;
failNext = false;
api.setRows([]);
return loadNext(api);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.more(api)">Load more</button>
<button type="button" :disabled="!api" @click="api && actions.fail(api)">Fail the next request</button>
<button type="button" :disabled="!api" @click="api && actions.reload(api)">From the start</button>
</div>
<Grid style="height: 440px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
orderNo: string;
customer: string;
}
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harmony Supply',
'Dawn Farms',
'Mode Fashion',
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: 'Order No.', width: 120 },
{ id: 'customer', title: 'Customer', width: 180 },
],
rows: [],
rowKey: 'id',
loading: true,
};
let say: (message: LogText) => void = () => {};
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: number): Promise<Row[]> =>
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] as string,
})),
);
}, 700),
);
// On failure, show the reason and a 'Retry' button right above the table (so it is visible without the log).
let box: HTMLElement | null = null;
let retry: (() => void) | null = null;
function showError(message: string): void {
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 = (): void => {
if (box) box.hidden = true;
};
async function loadNext(api: GridApi<Row>): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => loadNext(api),
// 'Make the next request fail'. It is not armed while loading or when there are no more rows to load.
fail: (api: GridApi<Row>) => {
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: GridApi<Row>) => {
if (busy) return say('Already loading');
page = 0;
failNext = false;
api.setRows([]);
return loadNext(api);
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.more(api)"
>Load more</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.fail(api)"
>Fail the next request</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.reload(api)"
>From the start</button>
</div>
<mx-grid style="height: 440px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
orderNo: string;
customer: string;
}
const PAGE_SIZE = 12;
const TOTAL = 40;
const customers = [
'Northwind Logistics',
'Bluesky Foods',
'Polaris Trading',
'Harmony Supply',
'Dawn Farms',
'Mode Fashion',
];
export const options: GridOptions<Row> = {
columns: [
{ id: 'orderNo', title: 'Order No.', width: 120 },
{ id: 'customer', title: 'Customer', width: 180 },
],
rows: [],
rowKey: 'id',
loading: true,
};
let say: (message: LogText) => void = () => {};
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: number): Promise<Row[]> =>
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] as string,
})),
);
}, 700),
);
// On failure, show the reason and a 'Retry' button right above the table (so it is visible without the log).
let box: HTMLElement | null = null;
let retry: (() => void) | null = null;
function showError(message: string): void {
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 = (): void => {
if (box) box.hidden = true;
};
async function loadNext(api: GridApi<Row>): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => loadNext(api),
// 'Make the next request fail'. It is not armed while loading or when there are no more rows to load.
fail: (api: GridApi<Row>) => {
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: GridApi<Row>) => {
if (busy) return say('Already loading');
page = 0;
failNext = false;
api.setRows([]);
return loadNext(api);
},
};