Skip to main content

use:enhance를 이용하면 브라우저의 기본 동작을 에뮬레이션하는 것보다 더 많은 일을 할 수 있습니다. 콜백을 제공함으로써 대기 상태낙관적 UI와 같은 기능을 추가할 수 있습니다. 두 액션에 인위적인 지연을 추가하여 느린 네트워크를 시뮬레이션해 봅시다.

src/routes/+page.server.js
export const actions = {
	create: async ({ cookies, request }) => {
		await new Promise((fulfil) => setTimeout(fulfil, 1000));
		...
	},

	delete: async ({ cookies, request }) => {
		await new Promise((fulfil) => setTimeout(fulfil, 1000));
		...
	}
};

항목을 생성하거나 삭제할 때, UI가 업데이트되기까지 1초가 걸리므로 사용자가 혼란스러워할 수 있습니다. 이를 해결하기 위해 로컬 상태를 추가합시다.

src/routes/+page.svelte
<script>
	import { fly, slide } from 'svelte/transition';
	import { enhance } from '$app/forms';

	export let data;
	export let form;

	let creating = false;
	let deleting = [];
</script>

그리고 첫 번째 use:enhance 안에서 creating을 토글합시다.

src/routes/+page.svelte
<form
	method="POST"
	action="?/create"
	use:enhance={() => {
		creating = true;

		return async ({ update }) => {
			await update();
			creating = false;
		};
	}}
>
	<label>
		add a todo:
		<input
			disabled={creating}
			name="description"
			value={form?.description ?? ''}
			autocomplete="off"
			required
		/>
	</label>
</form>

그러고 나면 데이터를 저장하는 동안 메시지를 표시할 수 있습니다.

src/routes/+page.svelte
<ul class="todos">
	<!-- ... -->
</ul>

{#if creating}
	<span class="saving">saving...</span>
{/if}

삭제의 경우, 서버가 무언가를 검증하기를 기다릴 필요가 없이 바로 UI를 업데이트할 수 있습니다.

src/routes/+page.svelte
<ul class="todos">
	{#each data.todos.filter((todo) => !deleting.includes(todo.id)) as todo (todo.id)}
		<li in:fly={{ y: 20 }} out:slide>
			<form
				method="POST"
				action="?/delete"
				use:enhance={() => {
					deleting = [...deleting, todo.id];
					return async ({ update }) => {
						await update();
						deleting = deleting.filter((id) => id !== todo.id);
					};
				}}
			>
				<input type="hidden" name="id" value={todo.id} />
				<button aria-label="Mark as complete"></button>

				{todo.description}
			</form>
		</li>
	{/each}
</ul>

use:enhance는 아주 다양하게 사용 가능합니다. 제출을 cancel()하거나, 리디렉션을 처리하고, 폼의 리셋 여부를 제어하는 등의 작업을 할 수 있습니다. 문서에서 자세한 내용을 확인하세요.

Next: API 라우트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<script>
	import { fly, slide } from 'svelte/transition';
	import { enhance } from '$app/forms';
 
	export let data;
	export let form;
</script>
 
<div class="centered">
	<h1>todos</h1>
 
	{#if form?.error}
		<p class="error">{form.error}</p>
	{/if}
 
	<form method="POST" action="?/create" use:enhance>
		<label>
			add a todo:
			<input
				name="description"
				value={form?.description ?? ''}
				autocomplete="off"
				required
			/>
		</label>
	</form>
 
	<ul class="todos">
		{#each data.todos as todo (todo.id)}
			<li in:fly={{ y: 20 }} out:slide>
				<form method="POST" action="?/delete" use:enhance>
					<input type="hidden" name="id" value={todo.id} />
					<span>{todo.description}</span>
					<button aria-label="Mark as complete" />
				</form>
			</li>
		{/each}
	</ul>
</div>
 
<style>
	.centered {
		max-width: 20em;
		margin: 0 auto;
	}
 
	label {
		width: 100%;
	}
 
	input {
		flex: 1;
	}
 
	span {
		flex: 1;
	}
 
	button {
		border: none;
		background: url(./remove.svg) no-repeat 50% 50%;
		background-size: 1rem 1rem;
		cursor: pointer;
		height: 100%;
		aspect-ratio: 1;
		opacity: 0.5;
		transition: opacity 0.2s;
	}
 
	button:hover {
		opacity: 1;
	}
 
	.saving {
		opacity: 0.5;
	}
</style>
 
initialising