Skip to content

Commit 61b34ca

Browse files
committed
docs: added entry for setting initial values async
1 parent 91bff18 commit 61b34ca

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<script setup>
2+
import { onMounted } from 'vue';
3+
import { useForm } from 'vee-validate';
4+
import * as yup from 'yup';
5+
6+
/**
7+
* Simulate fetching data from an API
8+
*/
9+
async function fetchData() {
10+
return new Promise(resolve => {
11+
setTimeout(() => {
12+
resolve({
13+
name: 'John Doe',
14+
15+
});
16+
}, 1500);
17+
});
18+
}
19+
20+
const { errors, resetForm, handleSubmit, defineInputBinds } = useForm({
21+
validationSchema: yup.object({
22+
email: yup.string().email().required(),
23+
name: yup.string().required(),
24+
}),
25+
});
26+
27+
const email = defineInputBinds('email');
28+
const name = defineInputBinds('name');
29+
30+
// Fetch data on mounted
31+
onMounted(async () => {
32+
const data = await fetchData();
33+
34+
resetForm({ values: data });
35+
});
36+
37+
const onSubmit = handleSubmit(values => {
38+
alert(JSON.stringify(values, null, 2));
39+
});
40+
</script>
41+
42+
<template>
43+
<form @submit="onSubmit">
44+
<input name="email" v-bind="email" />
45+
<span>{{ errors.email }}</span>
46+
47+
<input name="name" v-bind="name" />
48+
<span>{{ errors.name }}</span>
49+
50+
<button>Submit</button>
51+
</form>
52+
</template>

docs/src/pages/guide/composition-api/handling-forms.mdx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,14 @@ Here is an example that filters out some noisy initial values when submitting th
271271

272272
<Repl files={{ 'App.vue': 'CompositionHandlingForms12' }} client:only />
273273

274+
### Setting initial values asynchronously
275+
276+
Sometimes your data is fetched asynchronously from an API and you want to set the initial values or the current values after the data is fetched. You can do that by using `resetForm` to set both current and initial data.
277+
278+
<Repl files={{ 'App.vue': 'CompositionHandlingForms14' }} client:only />
279+
280+
You could alternatively use `setValues` but note that `setValues` can trigger validation and do not reset the meta state for the fields like `dirty` or `touched`.
281+
274282
## Handling Resets
275283

276284
vee-validate also handles form resets in a similar way to submissions. When resetting the form, all fields' errors will be cleared, meta info will be reset to defaults and the values will be reset to their original or initial values.

0 commit comments

Comments
 (0)