0
votes

I have 2 file upload in my form, i.e. Formik form with initialValues which is this

  const initialValues = {
    coverPhoto: this.props.response.response.coverPhoto
      ? this.props.response.response.coverPhoto
      : {},
    photo: this.props.response.response.photo
      ? this.props.response.response.photo
      : {}
  };

and the form

<Formik initialValues={initialValues}  onSubmit={fields => { this.props.onUpdateMyProfile(fields); }>
....
<input type="file" className="custom-file-input" id="photo" name="photo" accept="image/*" onChange={event => setFieldValue( "photo", event.currentTarget.files[0])}/>
<input type="file" className="custom-file-input" id="coverPhoto" name="coverPhoto" accept="image/*" onChange={event =>"coverPhoto", setFieldValue(event.target.files[0])} />

but when I submit the form it is getting me {} an empty object instead of the File Object, but when I console it out, I get the whole Object, along with the image object.

aboutYourself: "e4 e5 c4"
coverPhoto: ""
firstName: "Yash"
lastName: "Karanke"
photo: File
lastModified: 1605275591390
lastModifiedDate: Fri Nov 13 2020 19:23:11 GMT+0530 (India Standard Time) {}
name: "pngtree-abstract-background-image_88872.jpg"
size: 636889
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
slug: "yash-karanke"

. How do I resolve it?

2

2 Answers

0
votes

As per official docs, setFieldsValue expect 2 parameters-field and value.

setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void

<input type="file" 
  className="custom-file-input" 
  id="photo" 
  name="photo" 
  accept="image/*" 
  onChange={event => setFieldValue("photo",event.target.files[0])} />
0
votes

My solution is to append every field with FormData()

  <Formik initialValues={initialValues} onSubmit={fields => {
      let data = new FormData();
      data.append("photo", fields.photo);
      data.append("coverPhoto", fields.coverPhoto);
      data.append("firstName", fields.firstName);
      data.append("lastName", fields.lastName);
      data.append("email", fields.email);
      data.append("phoneNumber", fields.phoneNumber);
      data.append("zipcode", fields.zipcode);
      data.append("userLocation", fields.userLocation);
      data.append("aboutYourself", fields.aboutYourself);
      this.props.onUpdateMyProfile(data);
                        }}
>

If anyone wants to refactor this, please do so, I know the code is a messy.