currentPrescriptionMedsQuestion: yup.string().required('Required'), //----- need context value currentNonPrescriptionMedsQuestion: yup.string().required('Required'), currentPrescriptionMeds: yup.array(yup.object({ name: yup.string().when('currentPrescriptionMedsQuestion', { is: (val: string) => val === 'Yes', //----- val is undefined then: yup.string().required('Required'), otherwise: yup.string().notRequired() }).default(''), frequency: yup.string().when('currentPrescriptionMedsQuestion', { is: (val: string) => val === 'Yes', then: yup.string().required('Required'), otherwise: yup.string().notRequired() }).default(''), otherFrequency: yup.string().when('frequency', { is: (val: string) => val === 'Other', then: yup.string().default('').required('Required'), otherwise: yup.string().notRequired() }).default(''), dose: yup.string().when('currentPrescriptionMedsQuestion', { is: (val: string) => val === 'Yes', then: yup.string().default('').required('Required'), otherwise: yup.string().notRequired() }).default('') })),Estoy tratando de obtener el valor que necesito, pero cuando trato de registrarlo y enlazarlo, no estoy definido. ¿Cómo obtener un valor específico dentro de una matriz con un objeto ?
El problema ocurre cuando un campo anidado intenta acceder al valor de un campo antepasado y ya se informó aquí , para su caso, una solución es mover .when al campo principal currentPrescriptionMeds y podrá usar el valor de currentPrescriptionMedsQuestion para devolver el esquema correcto:
currentPrescriptionMedsQuestion: yup.string().required("Required"), //----- need context value currentNonPrescriptionMedsQuestion: yup.string().required("Required"), currentPrescriptionMeds: yup.array() .when( "currentPrescriptionMedsQuestion", (currentPrescriptionMedsQuestion, schema) => { const objSchema = yup.object({ name: yup.string().default(''), frequency: yup.string().default(''), otherFrequency: yup .string() .when("frequency", { is: (val) => val === "Other", then: yup.string().default("").required("Required"), otherwise: yup.string().notRequired() }) .default(""), dose: yup.string().default('') }); console.log("currentPrescriptionMedsQuestion:", currentPrescriptionMedsQuestion); if (currentPrescriptionMedsQuestion === "Yes") { // objSchema.fields.name.withMutation(schema => schema.required()); yup.reach(objSchema, "name") .withMutation((schema) => schema.required()); yup.reach(objSchema, "frequency") .withMutation((schema) => schema.required()); yup.reach(objSchema, "dose") .withMutation((schema) => schema.required()); } return yup.array(objSchema); } )Ejemplo de trabajo: