How can I send FormData with axios patch request?

Viewed 9012

I want to partially update a set of data and an image file. My image gets updated but the other data are not updated. Here is my code example:

    updateUsersData() {
    const { gender, phone, address, cityId, image, signature } = this.state;
    const fd = new FormData();
    fd.append('image', image, image.name);
    fd.append('gender', gender);
    fd.append('phone', phone);
    fd.append('address', address);
    fd.append('cityId', cityId);
    fd.append('signature', signature);
    fd.append('_method', 'PATCH');
    API.patch(`users/${this.props.id}`, 
        fd
        )
        .then(res => {

        })
        .catch(err => console.log(err))
}
2 Answers

I think that, the code is usefull for you

updateUsersData() {

  const { gender, phone, address, cityId, image, signature } = this.state;
  const fd = new FormData();
  fd.append('image', image, image.name);
  fd.append('gender', gender);
  fd.append('phone', phone);
  fd.append('address', address);
  fd.append('cityId', cityId);
  fd.append('signature', signature);
  fd.append('_method', 'PATCH');

  axios.post(
    `users/${this.props.id}`,
    fd,
    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
  );
}

https://github.com/axios/axios/issues/97

axios.patch() doesn't accept FormData.

However, it does accept a JSON.

You could then map FormData into a JSON. Or you can work with JSON from the start...

let userData = {};
fd.forEach(function(value, key){
    userData[key] = value;
});

axios.patch(`users/${this.props.id}`, userData);

I am pretty sure you don't need to define headers explicitly. Axios seems to do that internally.

Note:

patch method is for updating a part of a resource (just email and gender, etc...)

put method is for updating the resource as a whole.

EDIT: cleaner way to do this

Cleaner way to do this is just grabbing the whole form from a ref. For that you will need to import useRef from react and hook it with your form (for example ref='formRef') and then you don't need to append anything, you can just grab form data like so:

let fd = new FormData(formRef.current); // grabs form data as is
let userData = {}; // creates a user json
fd.forEach(function(value, key){
    userData[key] = value;  // populates user json with form data
});

axios.patch(`users/${this.props.id}`, userData);  // send user json to patch this resource
Related