Harry Wardana
Harry Wardana

Reputation: 277

input FormData reactjs hooks

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")
    }

}

Upvotes: 1

Views: 234

Answers (1)

Or Assayag
Or Assayag

Reputation: 6336

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')
});

Upvotes: 2

Related Questions