Loading Data from the Server
The destinations are written into the code twice, once as the options of the select and once as the list that the passport rule reads. A travel site loads them from its server, so the booking needs the loaded list as data from outside the form.
Fetching the Destinations
The API of the site sends each destination together with whether it is international:
export interface Destination {
readonly code: string
readonly city: string
readonly international: boolean
}
const LATENCY_MS = 400
const DESTINATIONS: ReadonlyArray<Destination> = [
{ code: 'denver', city: 'Denver', international: false },
{ code: 'seattle', city: 'Seattle', international: false },
{ code: 'lisbon', city: 'Lisbon', international: true },
{ code: 'tokyo', city: 'Tokyo', international: true },
]
export function fetchDestinations(): Promise<ReadonlyArray<Destination>> {
return new Promise(resolve => {
setTimeout(() => resolve(DESTINATIONS), LATENCY_MS)
})
}A timer stands in for the request.
Declaring the Destinations
Data from outside the form is a dependency as well. The booking is defined with defineGroupWithDeps and the type of the data, and reads the destinations from deps where the travelers get theirs:
const INTERNATIONAL_DESTINATIONS = ['lisbon', 'tokyo']
interface BookingDeps {
readonly destinations: ReadonlyArray<Destination>
}
export const bookingForm = defineGroup({
export const bookingForm = defineGroupWithDeps<BookingDeps>()({
schema: z.object({
tripType: z.enum(TRIP_TYPE, { error: 'Choose a trip type' }),
destination: z.string({ error: 'Choose a destination' }),
departureDate: z.iso.date({ error: 'Choose a departure date' }),
}),
children: { returnDate: returnDateField, travelers: travelersArray },
activeWhen: {
returnDate: ({ value }) => value.tripType == TRIP_TYPE.roundTrip,
},
childDeps: {
travelers: ({ value }) => ({
international: INTERNATIONAL_DESTINATIONS.some(code => code == value.destination),
travelers: ({ value, deps }) => ({
international: deps.destinations.some(
destination => destination.code == value.destination && destination.international,
),
}),
},
})childDeps receives the dependencies of the booking next to its value, and Destination is imported from the API as a type.
Passing the Destinations
The deps option of useForm passes the data as a getter over the list that the page loads, and the options of the select are built from the same list:
<script setup lang="ts">
import type { OutputOf } from '@formtree/vue'
import type { Destination } from './api'
import { provideFormNode, useForm } from '@formtree/vue'
import { shallowRef } from 'vue'
import { computed, ref, shallowRef } from 'vue'
import { fetchDestinations } from './api'
import { bookingForm, TRIP_TYPE } from './forms/booking'
import SelectField from './select-field.vue'
import TextField from './text-field.vue'
const TRIP_TYPE_OPTIONS = [
{ value: TRIP_TYPE.oneWay, label: 'One way' },
{ value: TRIP_TYPE.roundTrip, label: 'Round trip' },
]
const DESTINATION_OPTIONS = [
{ value: 'denver', label: 'Denver' },
{ value: 'seattle', label: 'Seattle' },
{ value: 'lisbon', label: 'Lisbon' },
{ value: 'tokyo', label: 'Tokyo' },
]
const destinations = ref<ReadonlyArray<Destination>>([])
const destinationOptions = computed(() =>
destinations.value.map(destination => ({
value: destination.code,
label: destination.city,
})),
)
const form = useForm(bookingForm)
const form = useForm(bookingForm, {
deps: () => ({ destinations: destinations.value }),
})
provideFormNode(form)
const returnDate = form.field('returnDate')
const travelers = form.array('travelers')
const booking = shallowRef<OutputOf<typeof bookingForm>>()
const bookTrip = form.handleSubmit(trip => {
booking.value = trip
})
fetchDestinations().then(list => {
destinations.value = list
})
</script>
<template>
<form novalidate @submit.prevent="bookTrip">
<SelectField name="tripType" label="Trip" :options="TRIP_TYPE_OPTIONS" />
<SelectField
name="destination"
label="Destination"
:options="DESTINATION_OPTIONS"
/>
<SelectField
name="destination"
label="Destination"
:options="destinationOptions"
/>
<TextField name="departureDate" label="Departure" type="date" />
<TextField
v-if="returnDate.state.active"
name="returnDate"
label="Return"
type="date"
/>
<fieldset v-for="traveler in travelers.items" :key="traveler.key">
<legend>Traveler {{ traveler.index + 1 }}</legend>
<TextField
:name="`travelers.${traveler.index}.fullName`"
label="Full name"
/>
<TextField
:name="`travelers.${traveler.index}.birthDate`"
label="Date of birth"
type="date"
/>
<TextField
v-if="traveler.field('passportNumber').state.active"
:name="`travelers.${traveler.index}.passportNumber`"
label="Passport number"
/>
<button type="button" @click="travelers.remove(traveler.index)">
Remove
</button>
</fieldset>
<button type="button" @click="travelers.push({})">Add traveler</button>
<p>{{ travelers.errorMessage }}</p>
<button type="submit">Book trip</button>
</form>
<pre v-if="booking">{{ booking }}</pre>
</template>The form reads the getter again when the list arrives, and the passport rule runs with the new destinations.
Why the Page Loads the Data
The page owns the request, so it determines when to load the list, how long to keep it, and what to show while it loads. The form reads whatever list it is given, and its rules follow the list as it changes.
Trying the Booking
The destinations fill the select a moment after the page opens. Add a traveler and choose Tokyo, and the passport number now follows the list the server sent.
<script setup lang="ts">
import type { OutputOf } from '@formtree/vue'
import type { Destination } from './api'
import { provideFormNode, useForm } from '@formtree/vue'
import { computed, ref, shallowRef } from 'vue'
import { fetchDestinations } from './api'
import { bookingForm, TRIP_TYPE } from './forms/booking'
import SelectField from './select-field.vue'
import TextField from './text-field.vue'
const TRIP_TYPE_OPTIONS = [
{ value: TRIP_TYPE.oneWay, label: 'One way' },
{ value: TRIP_TYPE.roundTrip, label: 'Round trip' },
]
const destinations = ref<ReadonlyArray<Destination>>([])
const destinationOptions = computed(() =>
destinations.value.map(destination => ({
value: destination.code,
label: destination.city,
})),
)
const form = useForm(bookingForm, {
deps: () => ({ destinations: destinations.value }),
})
provideFormNode(form)
const returnDate = form.field('returnDate')
const travelers = form.array('travelers')
const booking = shallowRef<OutputOf<typeof bookingForm>>()
const bookTrip = form.handleSubmit(trip => {
booking.value = trip
})
fetchDestinations().then(list => {
destinations.value = list
})
</script>
<template>
<form novalidate @submit.prevent="bookTrip">
<SelectField name="tripType" label="Trip" :options="TRIP_TYPE_OPTIONS" />
<SelectField
name="destination"
label="Destination"
:options="destinationOptions"
/>
<TextField name="departureDate" label="Departure" type="date" />
<TextField
v-if="returnDate.state.active"
name="returnDate"
label="Return"
type="date"
/>
<fieldset v-for="traveler in travelers.items" :key="traveler.key">
<legend>Traveler {{ traveler.index + 1 }}</legend>
<TextField
:name="`travelers.${traveler.index}.fullName`"
label="Full name"
/>
<TextField
:name="`travelers.${traveler.index}.birthDate`"
label="Date of birth"
type="date"
/>
<TextField
v-if="traveler.field('passportNumber').state.active"
:name="`travelers.${traveler.index}.passportNumber`"
label="Passport number"
/>
<button type="button" @click="travelers.remove(traveler.index)">
Remove
</button>
</fieldset>
<button type="button" @click="travelers.push({})">Add traveler</button>
<p>{{ travelers.errorMessage }}</p>
<button type="submit">Book trip</button>
</form>
<pre v-if="booking">{{ booking }}</pre>
</template><script setup lang="ts">
import { useField } from '@formtree/vue'
interface SelectOption {
readonly value: string
readonly label: string
}
const props = defineProps<{
name: string
label: string
options: ReadonlyArray<SelectOption>
}>()
const field = useField<string>(() => props.name)
</script>
<template>
<label :for="field.id">{{ label }}</label>
<select v-model="field.model" v-bind="field.attrs">
<option :value="undefined" disabled>Choose…</option>
<option v-for="option in options" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
<p :id="field.errorId">{{ field.errorMessage }}</p>
</template><script setup lang="ts">
import { useField } from '@formtree/vue'
const props = defineProps<{ name: string; label: string; type?: string }>()
const field = useField<string>(() => props.name)
</script>
<template>
<label :for="field.id">{{ label }}</label>
<input v-model="field.model" v-bind="field.attrs" :type="type" />
<p :id="field.errorId">{{ field.errorMessage }}</p>
</template>import type { Destination } from '../api'
import { arrayOf, defineField, defineGroupWithDeps } from '@formtree/vue'
import { z } from 'zod'
export const TRIP_TYPE = {
oneWay: 'oneWay',
roundTrip: 'roundTrip',
} as const
const ADULT_AGE = 18
const returnDateField = defineField({
schema: z.iso.date({ error: 'Choose a return date' }),
})
const passportNumberField = defineField({
schema: z.string({ error: 'Enter the passport number' }).trim().min(1, {
error: 'Enter the passport number',
}),
})
interface TravelerDeps {
readonly international: boolean
}
const travelerGroup = defineGroupWithDeps<TravelerDeps>()({
schema: z.object({
fullName: z.string({ error: 'Enter the full name' }).trim().min(1, {
error: 'Enter the full name',
}),
birthDate: z.iso.date({ error: 'Enter the date of birth' }),
}),
children: { passportNumber: passportNumberField },
activeWhen: {
passportNumber: ({ deps }) => deps.international,
},
})
const travelersArray = arrayOf(travelerGroup, {
validate: travelers => {
const hasAdult = travelers.some(traveler => isAdult(traveler.birthDate))
return hasAdult ? undefined : { code: 'Add an adult traveler' }
},
})
interface BookingDeps {
readonly destinations: ReadonlyArray<Destination>
}
export const bookingForm = defineGroupWithDeps<BookingDeps>()({
schema: z.object({
tripType: z.enum(TRIP_TYPE, { error: 'Choose a trip type' }),
destination: z.string({ error: 'Choose a destination' }),
departureDate: z.iso.date({ error: 'Choose a departure date' }),
}),
children: { returnDate: returnDateField, travelers: travelersArray },
activeWhen: {
returnDate: ({ value }) => value.tripType == TRIP_TYPE.roundTrip,
},
childDeps: {
travelers: ({ value, deps }) => ({
international: deps.destinations.some(
destination => destination.code == value.destination && destination.international,
),
}),
},
})
function isAdult(birthDate: string | undefined) {
if (birthDate == undefined) {
return false
}
const adultSince = new Date(birthDate)
adultSince.setFullYear(adultSince.getFullYear() + ADULT_AGE)
return adultSince <= new Date()
}export interface Destination {
readonly code: string
readonly city: string
readonly international: boolean
}
const LATENCY_MS = 400
const DESTINATIONS: ReadonlyArray<Destination> = [
{ code: 'denver', city: 'Denver', international: false },
{ code: 'seattle', city: 'Seattle', international: false },
{ code: 'lisbon', city: 'Lisbon', international: true },
{ code: 'tokyo', city: 'Tokyo', international: true },
]
export function fetchDestinations(): Promise<ReadonlyArray<Destination>> {
return new Promise(resolve => {
setTimeout(() => resolve(DESTINATIONS), LATENCY_MS)
})
}