Search code examples
reactjsnext.jsaxiosmultipartform-datareact-state

formData returns empty on first onSubmit call, but shows up as populated on second onSubmit call


when attempting to get data using formData the response on the first onSubmit action always returns an 'empty string' response, and then on the second i receive the data i actually expected to receive. so it works, just returns an empty string on the first run, any fixes?

    const [name, setName] = useState('')
    const [occupation, setOccupation] = useState('')
    const [paragraph, setParagraph] = useState('')
    const [date, setDate] = useState('')

    const handleName = ({target:{value}}) => setName(value)
    const handleOccupation = ({target:{value}}) => setOccupation(value)
    const handleParagraph = ({target:{value}}) => setParagraph(value)
    const handleDate = ({target:{value}}) => setDate(value)

    const [sendData, setSendData] = useState('')
    const [imagePreview, setImagePreview] = useState('')
    const [img, setImg] = useState('')
    const [imgName, setImgName] = useState('')

    const onImageChange = (e) => {
        setImagePreview(URL.createObjectURL(e.target.files[0]))
        setImg(e.target.files[0])
        setImgName(e.target.files[0].name)
    }

    const submitHandler = (e) => {
        e.preventDefault()
            const formDatas = new FormData()
            formDatas.append('name', name)
            formDatas.append('occupation', occupation)
            formDatas.append('bio', paragraph)
            formDatas.append('join', date)
            formDatas.append('image', img)
            setSendData(formDatas)
        console.log(sendData)
        // axios
        // .post(api + '/members', sendData)
        // .then(res => console.log(res))
        // .catch(err => console.log(err))
    }

Solution

  • Based on my comment, you could just post the formData directly :

    const submitHandler = (e) => {
      e.preventDefault();
      const formDatas = new FormData();
      formDatas.append("name", name);
      formDatas.append("occupation", occupation);
      formDatas.append("bio", paragraph);
      formDatas.append("join", date);
      formDatas.append("image", img);
      setSendData(formDatas);
      axios
      .post(api + '/members', formDatas)
      .then(res => console.log(res))
      .catch(err => console.log(err))
    };