Formik React выбрасывает ошибку при работе с массивами внутри объектов: Cannot read properties of undefined (reading 'push')

Рейтинг: 1Ответов: 1Опубликовано: 12.03.2023

У меня возникла проблема с работой с массивами, которые находятся на втором - третьем уровне объекта формы Formik.

Я вывожу этот массив при помощи FieldArray, обращаясь к содержимому при помощи arrayHelpers.form.values[arrayHelpers.name].conditions.

Вывести данные таким образом получается, но возникает другая проблема: при попытке добавить новую строку возникает ошибка:

Cannot read properties of undefined (reading 'push')

Полный код с ошибкой на Сэндбоксе https://codesandbox.io/s/heuristic-williams-6jocp1?file=/src/Formik.tsx:1039-1040

На данный момент элемент FieldArray выглядит так:

export const FieldArrayConditions = (arrayHelpers: any) => {
    const conditions = arrayHelpers.form.values[arrayHelpers.name].conditions
    return(
    <>
    {conditions.map((_: void, index: number) => {
        return (
            <div key={index} className='form__row-condition'>
                <input type='hidden' name={`${arrayHelpers.name}.conditions[${index}].id`}/>
                <input type='hidden' name={`${arrayHelpers.name}.conditions[${index}].margin_id`}/>
                <Field 
                    type='number'
                    name={`${arrayHelpers.name}.conditions[${index}].price_from`}
                    component={InputNotLabeled}
                    />
                <Field
                    name={`${arrayHelpers.name}.conditions[${index}].price_measure.id`}
                    component={SelectorCurrencies}
                    />
                <span>до</span>
                <Field 
                    type='number'
                    name={`${arrayHelpers.name}.conditions[${index}].price_before`}
                    component={InputNotLabeled}
                    />
                <Field
                    name={`${arrayHelpers.name}.conditions[${index}].price_measure.id`}
                    component={SelectorCurrencies}
                    />
                <span>=</span>
                <Field 
                    type='number'
                    placeholder='Сумма'
                    name={`${arrayHelpers.name}.conditions[${index}].margin`}
                    component={InputNotLabeled}
                    />
                <Field
                    name={`${arrayHelpers.name}.conditions[${index}].price_measure_id`}
                    component={SelectorCurrencies}
                    value={`${arrayHelpers.name}.conditions[${index}].price_measure.id`}
                    />
            </div>
        )
    })}
    <div className="form__fieldset">
        <BtnExport text={'Добавить условие'} 
        changeAction={() => arrayHelpers.push(initialConditions)}/>
    </div>
    </>
)}

Ответы

▲ 0

Вопрос решен - обращение к массиву через <FieldArray name="margin_avia_id.conditions" component={FieldArrayConditions}/>

Рабочий код https://codesandbox.io/s/heuristic-williams-6jocp1?file=/src/FieldArrayConditions.tsx