서버에서 받아 오는 동안 로딩과 실패 보여 주기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.
실행 화면은 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)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<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>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));// 처음에는 행이 없는 표예요. 서버에서 받은 행은 바깥(화면)이 들고 있다가 표에 넘겨 줘요.
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),
};<!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="reload">다시 불러오기</button>
<button type="button" id="fail">실패하는 요청 보내기</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 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면 오류로 끝나요. */
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 });
}
}
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;
};
}
const actions = {
reload: (api) => load(api, false),
fail: (api) => load(api, true),
};
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('reload').addEventListener('click', () => actions.reload(api));
document.getElementById('fail').addEventListener('click', () => actions.fail(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Grid } from '@maxgrid/react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { fetchRows, options, type Row } from './example';
// 서버에서 받은 행, 불러오는 중인지, 실패했는지는 모두 React 상태예요. 표에는 옵션으로 넘겨요.
export function ExampleGrid() {
const [rows, setRows] = useState<Row[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [attempt, setAttempt] = useState(0); // 올리면 다시 요청해요
const failNext = useRef(false);
useEffect(() => {
let alive = true; // 새 요청이 시작되거나 화면이 사라지면 옛 응답은 버려요
const fail = failNext.current;
failNext.current = false;
setLoading(true);
setError(null);
fetchRows(fail)
.then((result) => alive && setRows(result))
.catch((reason: Error) => alive && setError(reason.message))
.finally(() => alive && setLoading(false));
return () => {
alive = false;
};
}, [attempt]);
const gridOptions = useMemo(() => ({ ...options, rows, loading }), [rows, loading]);
return (
<>
<div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
<button type="button" onClick={() => setAttempt((n) => n + 1)}>
다시 불러오기
</button>
<button
type="button"
onClick={() => {
failNext.current = true;
setAttempt((n) => n + 1);
}}
>
실패하는 요청 보내기
</button>
</div>
{error && (
<p role="alert">
불러오지 못했어요: {error}{' '}
<button type="button" onClick={() => setAttempt((n) => n + 1)}>
다시 시도
</button>
</p>
)}
<div style={{ height: 260 }}>
<Grid<Row> options={gridOptions} />
</div>
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
orderNo: string;
customer: string;
amount: number;
}
// 처음에는 행이 없는 표예요. 서버에서 받은 행은 바깥(화면)이 들고 있다가 표에 넘겨 줘요.
export const options: GridOptions<Row> = {
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: boolean): Promise<Row[]> {
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: (message: LogText) => void = () => {};
let latest = 0;
let box: HTMLElement | null = null;
async function load(api: GridApi<Row>, fail: boolean): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => load(api, false),
fail: (api: GridApi<Row>) => load(api, true),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { Grid, type GridOptions } from '@maxgrid/vue';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { fetchRows, options, type Row } from './example';
// 서버에서 받은 행, 불러오는 중인지, 실패했는지는 모두 이 화면의 ref예요. 표에는 옵션으로 넘겨요.
const rows = ref<Row[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
let latest = 0; // 더 새 요청이 있으면 옛 응답은 버려요
async function load(fail = false) {
const request = ++latest;
loading.value = true;
error.value = null;
try {
const result = await fetchRows(fail);
if (request === latest) rows.value = result;
} catch (reason) {
if (request === latest) error.value = (reason as Error).message;
} finally {
if (request === latest) loading.value = false;
}
}
const gridOptions = computed<GridOptions<Row>>(() => ({
...options,
rows: rows.value,
loading: loading.value,
}));
onMounted(() => void load());
onBeforeUnmount(() => latest++); // 화면이 사라진 뒤에 오는 응답은 버려요
</script>
<template>
<div class="bar">
<button type="button" @click="load()">다시 불러오기</button>
<button type="button" @click="load(true)">실패하는 요청 보내기</button>
</div>
<p v-if="error" role="alert">
불러오지 못했어요: {{ error }}
<button type="button" @click="load()">다시 시도</button>
</p>
<Grid style="height: 260px" :options="gridOptions" />
</template>
<style scoped>
.bar {
display: flex;
gap: 8px;
margin-bottom: 8px;
}
</style>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
orderNo: string;
customer: string;
amount: number;
}
// 처음에는 행이 없는 표예요. 서버에서 받은 행은 바깥(화면)이 들고 있다가 표에 넘겨 줘요.
export const options: GridOptions<Row> = {
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: boolean): Promise<Row[]> {
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: (message: LogText) => void = () => {};
let latest = 0;
let box: HTMLElement | null = null;
async function load(api: GridApi<Row>, fail: boolean): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => load(api, false),
fail: (api: GridApi<Row>) => load(api, true),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, computed, signal, type OnDestroy, type OnInit } from '@angular/core';
import { GridComponent, type GridOptions } from '@maxgrid/angular';
import { fetchRows, options, type Row } from './example';
// 서버에서 받은 행, 불러오는 중인지, 실패했는지는 모두 signal이에요. 표에는 옵션으로 넘겨요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div style="display: flex; gap: 8px; margin-bottom: 8px">
<button type="button" (click)="load(false)">다시 불러오기</button>
<button type="button" (click)="load(true)">실패하는 요청 보내기</button>
</div>
@if (error()) {
<p role="alert">
불러오지 못했어요: {{ error() }}
<button type="button" (click)="load(false)">다시 시도</button>
</p>
}
<mx-grid style="height: 260px" [options]="gridOptions()" />
`,
})
export class ExampleGridComponent implements OnInit, OnDestroy {
private readonly rows = signal<Row[]>([]);
private readonly loading = signal(true);
readonly error = signal<string | null>(null);
private latest = 0; // 더 새 요청이 있으면 옛 응답은 버려요
readonly gridOptions = computed<GridOptions<Row>>(() => ({
...options,
rows: this.rows(),
loading: this.loading(),
}));
ngOnInit(): void {
void this.load(false);
}
ngOnDestroy(): void {
this.latest++; // 화면이 사라진 뒤에 오는 응답은 버려요
}
async load(fail: boolean): Promise<void> {
const request = ++this.latest;
this.loading.set(true);
this.error.set(null);
try {
const result = await fetchRows(fail);
if (request === this.latest) this.rows.set(result);
} catch (reason) {
if (request === this.latest) this.error.set((reason as Error).message);
} finally {
if (request === this.latest) this.loading.set(false);
}
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
orderNo: string;
customer: string;
amount: number;
}
// 처음에는 행이 없는 표예요. 서버에서 받은 행은 바깥(화면)이 들고 있다가 표에 넘겨 줘요.
export const options: GridOptions<Row> = {
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: boolean): Promise<Row[]> {
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: (message: LogText) => void = () => {};
let latest = 0;
let box: HTMLElement | null = null;
async function load(api: GridApi<Row>, fail: boolean): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => load(api, false),
fail: (api: GridApi<Row>) => load(api, true),
};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="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>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));// 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),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Show loading and failure while fetching from a server</title>
</head>
<body>
<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>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 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.
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. */
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 });
}
}
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;
};
}
const actions = {
reload: (api) => load(api, false),
fail: (api) => load(api, true),
};
options.ariaLabel = "Show loading and failure while fetching from a server";
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('reload').addEventListener('click', () => actions.reload(api));
document.getElementById('fail').addEventListener('click', () => actions.fail(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Grid } from '@maxgrid/react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { fetchRows, options, type Row } from './example';
// 서버에서 받은 행, 불러오는 중인지, 실패했는지는 모두 React 상태예요. 표에는 옵션으로 넘겨요.
export function ExampleGrid() {
const [rows, setRows] = useState<Row[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [attempt, setAttempt] = useState(0); // 올리면 다시 요청해요
const failNext = useRef(false);
useEffect(() => {
let alive = true; // 새 요청이 시작되거나 화면이 사라지면 옛 응답은 버려요
const fail = failNext.current;
failNext.current = false;
setLoading(true);
setError(null);
fetchRows(fail)
.then((result) => alive && setRows(result))
.catch((reason: Error) => alive && setError(reason.message))
.finally(() => alive && setLoading(false));
return () => {
alive = false;
};
}, [attempt]);
const gridOptions = useMemo(() => ({ ...options, rows, loading }), [rows, loading]);
return (
<>
<div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
<button type="button" onClick={() => setAttempt((n) => n + 1)}>
다시 불러오기
</button>
<button
type="button"
onClick={() => {
failNext.current = true;
setAttempt((n) => n + 1);
}}
>
실패하는 요청 보내기
</button>
</div>
{error && (
<p role="alert">
불러오지 못했어요: {error}{' '}
<button type="button" onClick={() => setAttempt((n) => n + 1)}>
다시 시도
</button>
</p>
)}
<div style={{ height: 260 }}>
<Grid<Row> options={gridOptions} />
</div>
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
orderNo: string;
customer: string;
amount: number;
}
// 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: GridOptions<Row> = {
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: boolean): Promise<Row[]> {
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: (message: LogText) => void = () => {};
let latest = 0;
let box: HTMLElement | null = null;
async function load(api: GridApi<Row>, fail: boolean): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => load(api, false),
fail: (api: GridApi<Row>) => load(api, true),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { Grid, type GridOptions } from '@maxgrid/vue';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { fetchRows, options, type Row } from './example';
// 서버에서 받은 행, 불러오는 중인지, 실패했는지는 모두 이 화면의 ref예요. 표에는 옵션으로 넘겨요.
const rows = ref<Row[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
let latest = 0; // 더 새 요청이 있으면 옛 응답은 버려요
async function load(fail = false) {
const request = ++latest;
loading.value = true;
error.value = null;
try {
const result = await fetchRows(fail);
if (request === latest) rows.value = result;
} catch (reason) {
if (request === latest) error.value = (reason as Error).message;
} finally {
if (request === latest) loading.value = false;
}
}
const gridOptions = computed<GridOptions<Row>>(() => ({
...options,
rows: rows.value,
loading: loading.value,
}));
onMounted(() => void load());
onBeforeUnmount(() => latest++); // 화면이 사라진 뒤에 오는 응답은 버려요
</script>
<template>
<div class="bar">
<button type="button" @click="load()">다시 불러오기</button>
<button type="button" @click="load(true)">실패하는 요청 보내기</button>
</div>
<p v-if="error" role="alert">
불러오지 못했어요: {{ error }}
<button type="button" @click="load()">다시 시도</button>
</p>
<Grid style="height: 260px" :options="gridOptions" />
</template>
<style scoped>
.bar {
display: flex;
gap: 8px;
margin-bottom: 8px;
}
</style>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
orderNo: string;
customer: string;
amount: number;
}
// 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: GridOptions<Row> = {
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: boolean): Promise<Row[]> {
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: (message: LogText) => void = () => {};
let latest = 0;
let box: HTMLElement | null = null;
async function load(api: GridApi<Row>, fail: boolean): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => load(api, false),
fail: (api: GridApi<Row>) => load(api, true),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, computed, signal, type OnDestroy, type OnInit } from '@angular/core';
import { GridComponent, type GridOptions } from '@maxgrid/angular';
import { fetchRows, options, type Row } from './example';
// 서버에서 받은 행, 불러오는 중인지, 실패했는지는 모두 signal이에요. 표에는 옵션으로 넘겨요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div style="display: flex; gap: 8px; margin-bottom: 8px">
<button type="button" (click)="load(false)">다시 불러오기</button>
<button type="button" (click)="load(true)">실패하는 요청 보내기</button>
</div>
@if (error()) {
<p role="alert">
불러오지 못했어요: {{ error() }}
<button type="button" (click)="load(false)">다시 시도</button>
</p>
}
<mx-grid style="height: 260px" [options]="gridOptions()" />
`,
})
export class ExampleGridComponent implements OnInit, OnDestroy {
private readonly rows = signal<Row[]>([]);
private readonly loading = signal(true);
readonly error = signal<string | null>(null);
private latest = 0; // 더 새 요청이 있으면 옛 응답은 버려요
readonly gridOptions = computed<GridOptions<Row>>(() => ({
...options,
rows: this.rows(),
loading: this.loading(),
}));
ngOnInit(): void {
void this.load(false);
}
ngOnDestroy(): void {
this.latest++; // 화면이 사라진 뒤에 오는 응답은 버려요
}
async load(fail: boolean): Promise<void> {
const request = ++this.latest;
this.loading.set(true);
this.error.set(null);
try {
const result = await fetchRows(fail);
if (request === this.latest) this.rows.set(result);
} catch (reason) {
if (request === this.latest) this.error.set((reason as Error).message);
} finally {
if (request === this.latest) this.loading.set(false);
}
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
orderNo: string;
customer: string;
amount: number;
}
// 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: GridOptions<Row> = {
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: boolean): Promise<Row[]> {
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: (message: LogText) => void = () => {};
let latest = 0;
let box: HTMLElement | null = null;
async function load(api: GridApi<Row>, fail: boolean): Promise<void> {
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: GridApi<Row>, log: (message: LogText) => void) {
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: GridApi<Row>) => load(api, false),
fail: (api: GridApi<Row>) => load(api, true),
};