비동기 처리
Grunfeld의 강력한 기능 중 하나는 비동기 작업을 자연스럽게 처리할 수 있다는 점입니다. 대화상자 생성 시 비동기 작업을 수행하거나, 여러 대화상자를 순차적으로 표시할 수 있습니다.
로딩 대화상자#
비동기 작업 중 로딩 상태를 표시하는 대화상자를 만들 수 있습니다:
const loadData = async () => {
const promise = grunfeld.add<string>(async (removeWith) => {
// First, show loading UI
const loadingElement = (
<div style={{ padding: "20px", textAlign: "center" }}>
<p>Loading user information...</p>
<div>⏳</div>
</div>
);
// Perform async operation
try {
const data = await fetch("/api/user").then((r) => r.json());
// To update UI after successful load,
// you need to create a new dialog or use state management
removeWith(data);
} catch (error) {
// Close with error on failure
removeWith(null);
}
return loadingDialog;
});
const result = await promise;
console.log("Loaded data:", result);
};순차적 대화상자#
여러 대화상자를 순차적으로 표시하여 복잡한 워크플로우를 구현할 수 있습니다:
const runWorkflow = async () => {
// Step 1: Email input
const email = await grunfeld.add<string>((removeWith) => ({
element: <EmailInput onSubmit={removeWith} />,
}));
if (!email) return;
// Step 2: Password input
const password = await grunfeld.add<string>((removeWith) => ({
element: <PasswordInput email={email} onSubmit={removeWith} />,
}));
if (!password) return;
// Step 3: Confirmation
const confirmed = await grunfeld.add<boolean>((removeWith) => ({
element: (
<div>
<p>Do you want to sign up with this information?</p>
<p>Email: {email}</p>
<button onClick={() => removeWith(true)}>Sign Up</button>
<button onClick={() => removeWith(false)}>Cancel</button>
</div>
),
}));
if (confirmed) {
await signup(email, password);
}
};타임아웃 처리#
일정 시간 후 자동으로 대화상자를 닫고 Promise를 처리할 수 있습니다:
const showTimedDialog = async () => {
const dialogPromise = grunfeld.add<boolean>((removeWith) => ({
element: (
<div>
<p>Please respond within 10 seconds</p>
<button onClick={() => removeWith(true)}>Confirm</button>
<button onClick={() => removeWith(false)}>Cancel</button>
</div>
),
}));
// Auto-close after 10 seconds
const timeoutId = setTimeout(() => {
grunfeld.remove();
}, 10000);
const result = await dialogPromise;
clearTimeout(timeoutId);
if (result === undefined) {
console.log("Closed due to timeout");
} else if (result) {
console.log("User selected confirm");
} else {
console.log("User selected cancel");
}
};