How To Use OnSubmit with Dropzone?

388 Views Asked by At

I am using dropzone to upload an image to amazon s3 but would like the image to be uploaded once I press the submit button, not upon "dropping" the image. How could I do this? This is the code I have. Whenever I try to drop the image I can error: Unhandled Rejection (TypeError): event.preventDefault is not a function

import React, { useState } from 'react'
import { Typography, Button, Form, message, Input, Icon } from 'antd';
import FileUpload from '../../utils/FileUpload'
import Axios from 'axios';
import Dropzone from 'react-dropzone';
import download from './download.jpeg'



const { Title } = Typography;
const { TextArea } = Input;

 
const Continents = [
    { key: 1, value: "1" },
    { key: 2, value: "2" },
    { key: 3, value: "3" },
    { key: 4, value: "4" },
    { key: 5, value: "5" },
    { key: 6, value: "6" },
    { key: 7, value: "7" }
]


function UploadProductPage(props) {

    const [TitleValue, setTitleValue] = useState("")
    const [DescriptionValue, setDescriptionValue] = useState("")
    const [PriceValue, setPriceValue] = useState(0)
    const [ContinentValue, setContinentValue] = useState([])
    const [Images, setImages] = useState([])

    const onTitleChange = (event) => {
        setTitleValue(event.currentTarget.value)
    }

    const onDescriptionChange = (event) => {
        setDescriptionValue(event.currentTarget.value)
    }

    const onPriceChange = (event) => {
        setPriceValue(event.currentTarget.value)
    }

    const onContinentsSelectChange = (event) => {
        setContinentValue(event.currentTarget.value)
    }

    const updateImages = (newImages) => {
        setImages(newImages)
    }


    ///////// on drop stuff 

  
    const onSubmit = (event, files) => {
        event.preventDefault();


        if (!TitleValue || !DescriptionValue || !PriceValue ||
            !ContinentValue || !Images) {
            return alert('fill all the fields first!')
        }

        const variables = {
            writer: props.user.userData._id,
            title: TitleValue,
            description: DescriptionValue,
            price: PriceValue,
            images: Images,
            continents: ContinentValue,
        }

        Axios.post('/api/product/uploadProduct', variables)
            .then(response => {
                if (response.data.success) {
                    alert('Product Successfully Uploaded')
                    props.history.push({
                        pathname: "/user/cart",
                        state: {
                          data: variables,
                        }, 
                      })
                } else {
                    alert('Failed to upload Product')
                }
            })
            
            let formData = new FormData();
            const config = {
                header: {
                    'accept': 'application/json',
                    'Accept-Language': 'en-US,en;q=0.8',
                    'Content-Type': `multipart/form-data; boundary=${formData._boundary}`
                }
            }
            formData.append("galleryImage", files)
            //save the Image we chose inside the Node Server 
            Axios.post('/api/photo/uploadMultiple', formData, config)
                .then(response => {
                    if (response.data.success) {
    
                        setImages([...Images, response.data.image])
                        props.refreshFunction([...Images, response.data.image])
    
                    } else {
                        alert('Failed to save the Image in Server')
                    }
                })
    }

    return (
        
        <div style={{ maxWidth: '700px', margin: '2rem auto' }}>
            <div style={{ textAlign: 'center', marginBottom: '2rem' }}>
                <Title level={2}> Upload Prompt </Title>

    
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            

        </div>
            


            <Form onSubmit={onSubmit} >

                {/* DropZone */}
                <div >
             <Dropzone
                onDrop={onSubmit}
                multiple={false}
                maxSize={800000000}
            >
                {({ getRootProps, getInputProps }) => (
                    <div style={{
                        width: '300px', height: '240px', border: '1px solid lightgray',
                        display: 'flex', alignItems: 'center', justifyContent: 'center'
                    }}
                        {...getRootProps()}
                    >
                        {console.log('getRootProps', { ...getRootProps() })}
                        {console.log('getInputProps', { ...getInputProps() })}
                        <input {...getInputProps()} />
                        <Icon type="plus" style={{ fontSize: '3rem' }} />

                    </div>
                )}
            </Dropzone>
        </div>

                <br />
                <br />
                <label>Subject</label>
                <Input
                    onChange={onTitleChange}
                    value={TitleValue}
                />
                <br />
                <br />
                <label>Title</label>
                <Input
                    onChange={onDescriptionChange}
                    value={DescriptionValue}
                />
                <br />
                <br />
                <label>Pages</label>
                <Input
                    onChange={onPriceChange}
                    value={PriceValue}
                    type="number"
                />
                <br /><br />
                <label>Due Date</label>
                <br /><br />
                <Input onChange={onContinentsSelectChange} value={ContinentValue}
                    type="date"
                />
                <br />
                <br />
                <Button
                    onClick={onSubmit}
                >
                    Submit
                </Button>
            </Form>
        </div>
    )
}

export default UploadProductPage
1

There are 1 best solutions below

0
On

I just faced the same problem today - for anyone in the future, here's the solution for react-dropzone-uploader... just lookup the props for react-dropzone as they're probably very similar so this is still applicable (noticed the diff libraries after commenting - roll eyes)

  1. use the submitButtonContent prop and create your own button
  2. use a callback to get access to the event
  3. use e.preventDefault() or something of the likes...

I couldn't manage to get access to the event via the original props that're standard with "react-dropzone-uploader" configuration

submitButtonContent={() => (
    <button onClick={(e) => {
       e.preventDefault();
                                                    
                                                    
       console.log("SUBMIT!");
   }} className="btn btn-secondary" style={{ width: "100%" }}>Submit File</button>
)}

something like that! (notice the return brackets)