0

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))
    }
ieatglue
  • 25
  • 1
  • 4
  • I'm assuming you're talking about the `console.log` . setState is async so in order to log the state immediately after setting it you would need to use a useEffect. Here is a good explanation https://stackoverflow.com/a/54713679/15474532 – Ryan Zeelie Jan 01 '23 at 10:03

2 Answers2

0

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))
}; 
Ryan Zeelie
  • 1,320
  • 5
  • 12
0

I believe your issue is essentially the same as this person's: React hooks functions have old version of a state var

Based on the top answer there, you may have to use refs instead of state.

Bets
  • 506
  • 2
  • 12