Search code examples
javascriptreactjsajaxreact-hooksuse-effect

Simple React file upload, form data not appending


     const [image, setImage] = useState({ preview: "", file: "" });
     const handleChange = (e) => {
        e.preventDefault();
        if (e.target.files.length) {
          setImage({
            preview: URL.createObjectURL(e.target.files[0]),
            file: e.target.files[0],
          });
        }
      };
      useEffect(() => {
        const formData = new FormData();
        formData.append("file", image.file);
        console.log(formData);
      }, [image]);

In the above code console.log(formData); returns empty object, unable to send file on axios


Solution

  • You cannot print FormData to see the entries. https://developer.mozilla.org/en-US/docs/Web/API/FormData

    You need to get it with key: formData.get('file') should give you what you need to verify.