Fixed dynamic summary page and storing of context formData values.

This commit is contained in:
Samuel Andert 2023-08-08 10:16:38 +02:00
parent b5cd51e125
commit 7038cf50cf
2 changed files with 15 additions and 17 deletions

View File

@ -29,30 +29,23 @@
const formMachine = createMachine({
id: 'form',
initial: 'start',
initial: 'input',
context: {
currentField: 0,
formData: initialFormData
},
states: {
start: {
on: {
NEXT: 'input'
}
},
input: {
on: {
NEXT: [
{
target: 'submitting',
actions: [
assign({
formData: (context) => ({
...context.formData,
[fields[context.currentField].name]: form[fields[context.currentField].name]
})
actions: assign({
formData: (context, event) => ({
...context.formData,
[fields[context.currentField].name]: event.fieldValue
})
],
}),
cond: (context) => context.currentField === fields.length - 1
},
{
@ -60,9 +53,9 @@
actions: [
assign({
currentField: (context) => context.currentField + 1,
formData: (context) => ({
formData: (context, event) => ({
...context.formData,
[fields[context.currentField].name]: form[fields[context.currentField].name]
[fields[context.currentField].name]: event.fieldValue
})
})
]
@ -98,7 +91,12 @@
return;
}
send('NEXT');
const fieldValue = $form[currentFieldName];
console.log(`Current input value: ${fieldValue}`);
send('NEXT', { fieldValue });
// Log the context formData
console.log(`Context formData: ${JSON.stringify($state.context.formData)}`);
}
function handleKeyDown(event) {

View File

@ -30,7 +30,7 @@ const validationMessages = {
export const UserSchema = z.object({
name: z.string().nonempty('Name is required.').min(3, validationMessages.name.minLength).max(10, validationMessages.name.maxLength),
email: z.string().nonempty('Email is required.').email(validationMessages.email.isEmail),
email: z.string().email(validationMessages.email.isEmail),
about: z.string().max(500, validationMessages.about.maxLength),
age: z.number().min(18, validationMessages.age.min).max(120, validationMessages.age.max),
favoriteFood: z.enum(['apple', 'banana', 'coconut', 'strawberry', 'mango']).refine(value => value !== '', validationMessages.favoriteFood.invalid),