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({ const formMachine = createMachine({
id: 'form', id: 'form',
initial: 'start', initial: 'input',
context: { context: {
currentField: 0, currentField: 0,
formData: initialFormData formData: initialFormData
}, },
states: { states: {
start: {
on: {
NEXT: 'input'
}
},
input: { input: {
on: { on: {
NEXT: [ NEXT: [
{ {
target: 'submitting', target: 'submitting',
actions: [ actions: assign({
assign({ formData: (context, event) => ({
formData: (context) => ({ ...context.formData,
...context.formData, [fields[context.currentField].name]: event.fieldValue
[fields[context.currentField].name]: form[fields[context.currentField].name]
})
}) })
], }),
cond: (context) => context.currentField === fields.length - 1 cond: (context) => context.currentField === fields.length - 1
}, },
{ {
@ -60,9 +53,9 @@
actions: [ actions: [
assign({ assign({
currentField: (context) => context.currentField + 1, currentField: (context) => context.currentField + 1,
formData: (context) => ({ formData: (context, event) => ({
...context.formData, ...context.formData,
[fields[context.currentField].name]: form[fields[context.currentField].name] [fields[context.currentField].name]: event.fieldValue
}) })
}) })
] ]
@ -98,7 +91,12 @@
return; 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) { function handleKeyDown(event) {

View File

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