useDraft
A form draft: what the user typed is saved to localStorage and restored after a page reload or a later visit. It is removed automatically when the form is submitted successfully or reset.
Signature
ts
function useDraft(form: Form, key: string, options?: { storage?: StorageLike; debounce?: number }): { restored: boolean; clear(): void }| Parameter | Description |
|---|---|
key | Storage key. Different for different forms: 'signup', `post-${id}` |
options.storage | localStorage by default. sessionStorage keeps the draft until the tab is closed |
options.debounce | Delay before saving, ms. Default 300 |
Returns restored — whether a draft was restored (e.g. to show "Draft restored") — and clear().
Notes
- The draft is written only while there are unsaved changes (
form.dirty). - Don't keep passwords or card data in a draft:
localStorageis readable by any script on the page. - On the server (SSR) there is no storage —
useDraftdoes nothing.
Example
vue
<script setup lang="ts">
const form = useForm(Post, { initial: { title: '', body: '' } });
const draft = useDraft(form, 'new-post');
useLeaveGuard(form);
</script>
<template>
<p v-if="draft.restored">Draft restored · <button type="button" @click="form.reset()">Discard</button></p>
</template>