Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setFieldValue, Formik and InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement'

I'm trying to upload a file using Formik and setFieldValue.

I don't understand why i'm getting

InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element > accepts a filename, which may only be programmatically set to the empty string.

When i'm uploading a file

I have some knowledge of React, but it's my first time with Formik.

Some (maybe useful) code

export const ImageUploaderField = ({ ...props }) => {
    const { setFieldValue } = useFormikContext()
    const [field] = useField(props)
    return (
        <Field
            {...field}
            {...props}
            onChange={(event) => {
                setFieldValue(field.name, event.currentTarget.files)
            }}
        />
    )
}

Call site

<ImageUploaderField name="filename" type="file" />

like image 404
Stéphane Avatar asked Sep 01 '25 16:09

Stéphane


2 Answers

I was having the same error. Got it working by adding a value={undefined} prop to <input> element.

like image 148
Camilo Avatar answered Sep 04 '25 13:09

Camilo


Instead of adding value={undefined}, ignore adding value property to Field

export const ImageUploaderField = ({ ...props }) => {
    const { setFieldValue } = useFormikContext()
    const [field] = useField(props)
    const {value, ...rest} = field;
    return (
        <Field
            {...rest}
            {...props}
            onChange={(event) => {
                setFieldValue(field.name, event.currentTarget.files)
            }}
        />
    )
}
like image 41
Mahalingam Sundararaj Avatar answered Sep 04 '25 13:09

Mahalingam Sundararaj