0

i am trying to submit a form using patch in react js i want to merge Values & formData so that i can pass it a single variable throgh the api but i am getting error when i do that i have also created a codesandbox for refernce

const [Values, setValues] = useState();
  const [image, setImage] = useState();
  const changeHandler = (e) => {
    setValues({ ...Values, [e.target.name]: e.target.value });
  };
const FileHandler = (e) => {
    setImage(e.target.files[0]);
     };

 const submitValue = (e) => {
  
    e.preventDefault();
    const formData = new FormData();
    formData.append("prescription", image);

    // setValues({ ...Values, formData });  // not able to do this 
    const config = {
      headers: {
        Authorization: `token ` + localStorage.getItem("token"),
    
      },
    };
    console.log(image);
    console.log(Values);
    axios
      .patch("profile-update/", Values, config)// as i am passing `fromdata` i am able to pacth the image if i use Values form input data is able to pass i am trying to pass both
      .then(() => {
        alert("updated data");
      })
      .catch((error) => {
        alert(JSON.stringify(error.response));
      });

i have created this working sandbox https://codesandbox.io/s/cocky-jepsen-ejiuc?file=/src/App.js:270-278

vivek kn
  • 107
  • 1
  • 18
  • 45
  • Does this answer your question? [Updating and merging state object using React useState() hook](https://stackoverflow.com/questions/55342406/updating-and-merging-state-object-using-react-usestate-hook) – Vikas Nov 29 '21 at 05:20
  • i dont undersand how this is going to help me – vivek kn Nov 29 '21 at 05:28

1 Answers1

0

Combine Values to formData and pass the formData patch.

const formData = new FormData();
formData.append("prescription", image);

Object.entries(Values).forEach(([key, value]) => formData.append(key, value));

axios.patch("profile-update/", formData, config);
Siva K V
  • 10,561
  • 2
  • 16
  • 29
  • @ siva Kv this is working only when i have data both image and values , if any one of this is not passed to the api i get error – vivek kn Nov 29 '21 at 09:11