1

I'm learning react js, here I am making an input to the database. here I have a problem how to send data with the format FormData (); use hooks ?

const initialFormState = { id: null, id_user: '1', kode: '', qty: '', harga: '' }
  
    const [ibarang, setIbarang] = useState(initialFormState);

    const handleInputChange = (e) => {
        const { name, value } = e.target
        setIbarang({ ...ibarang, [name]: value })

    }

    const handleSubmitBarang = async (e) => {
        e.preventDefault()
        console.log(ibarang);
        try {
        let res = await Axios.post('https://API.COM', ibarang, {
            'Content-Type': 'application/x-www-form-urlencoded',
        })
        console.log(res.data)
        if (res.data.status === 200) {
            setTimeout(() => {
                // history.push("/dashboard")
            }, 500);
        } else if (res.data.status === 401) {
            setalertMessage("Username atau password salah!")
        } else {
            setalertMessage("Periksa kembali koneksi internet anda")
        }
    } catch (error) {
        setalertMessage("Periksa kembali koneksi internet anda")
    }

}
4
  • What you try to do? send the data to the server? Commented Nov 20, 2020 at 20:17
  • 1
    posting data, because the backend uses form-data Commented Nov 20, 2020 at 20:19
  • well, you can use any package you want to send the data to the server. I would recommend to use something more simple, like axios, to send simple JSON strings. Give it a try. Commented Nov 20, 2020 at 20:23
  • 1
    I have updated my code above, I mean, how about use let FormData = require ('form-data'); let data = new FormData (); Commented Nov 20, 2020 at 20:26

1 Answer 1

2

First, add the axios NPM package by

npm i axios

Second, try something like:

import axios from 'axios';

// Submit the form data 
axios.post('https://API.COM', 
  JSON.stringify(ibarang)
).then(response => {
  console.log('Submit Success')
}).catch(e => {
  console.log('Submit Fail')
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.