Home > Software design >  FormData not letting me append file in React Js using typescript
FormData not letting me append file in React Js using typescript

Time:10-22

I want to send a File in my request using React Js, but I am unable to append file in object of FormData using typescript. Here's my React Js Code

    const [imageFile, setImageFile] = React.useState();
      const [productImageMutation, productImageMutationResult]=useAddProductImageMutation();
      const handleUploadClick = (e: any) => {
      var file = e.target.files[0];
      setImageFile(file);
  };
  const handleOnSubmit = (values: Picture) => {
      const formData = new FormData();
      formData.append("formFile", imageFile); //It Gives Error there.
    productImageMutation({ data: formData});
  };

enter image description here

CodePudding user response:

You should define your types correctly. Furthermore possible errors also should be handled as well.

const [imageFile, setImageFile] = React.useState<File>();

  const handleSelectFile = (event: React.ChangeEvent<HTMLInputElement>) => {
    if(event.target.files) {
      var file = event.target.files[0];
      setImageFile(file);
    }
  }

  const handleOnSubmit = (values: Picture) => {
    if(imageFile) {
      const formData = new FormData();
      formData.append("formFile", imageFile);
      productImageMutation({ data: formData});
    }else {
      // Display an error in this block
      // No file selected
     }

  };

CodePudding user response:

Try to update your state initialization

const [imageFile, setImageFile] = React.useState('');

And also mention a type to you state because in TS you must provide a type

  • Related