Skip to content

Instantly share code, notes, and snippets.

@hscstudio
Created July 20, 2020 09:19
Show Gist options
  • Save hscstudio/821fbdf2dbb39fa3e1ab376b36665c2f to your computer and use it in GitHub Desktop.
Save hscstudio/821fbdf2dbb39fa3e1ab376b36665c2f to your computer and use it in GitHub Desktop.
import React from 'react'
import { useHistory, useParams } from 'react-router-dom'
import Axios from 'axios'
const getProduct = async (productId, callback) => {
try {
const response = await Axios.get(`http://localhost:3000/product/${productId}`)
console.log(response)
callback(response.data)
} catch (error) {
const response = {
status: 'error',
message: 'Network error'
}
callback(response)
}
}
const Update = () => {
const history = useHistory()
const { productId } = useParams()
const [product, setProduct] = React.useState({
name: '',
price: 0,
stock: 1,
status: true
})
const [initial, setInitial] = React.useState(true)
React.useEffect(() => {
if (initial) {
getProduct(productId, response => {
const { status, message, data } = response
if (status === 'success') {
setProduct(data)
} else {
alert(message)
}
setInitial(false)
})
}
}, [])
const handleChange = (e, name) => {
const value = e.target.value
setProduct({ ...product, [name]: value })
}
const handleSubmit = async (e) => {
e.preventDefault()
try {
const response = await Axios.put(`http://localhost:3000/product/${productId}`, product)
const { status, message } = response.data
if (status === 'success') {
alert(message)
history.push('/product')
} else {
alert(message)
}
} catch (error) {
alert('Network error')
}
}
return <>
<h2>Halaman Form Create Product</h2>
<form>
<label>Name </label>
<input type="text" size={50} value={product.name} onChange={(e) => handleChange(e, 'name')} />
<label>Price </label>
<input type="number" value={product.price} onChange={(e) => handleChange(e, 'price')} />
<label>Stock </label>
<input type="number" size={30} value={product.stock} onChange={(e) => handleChange(e, 'stock')} />
<label>Status </label>
<select value={product.status} onChange={(e) => handleChange(e, 'status')}>
<option value={false}>off</option>
<option value={true}>on</option>
</select>
<label></label>
<button onClick={ handleSubmit }> submit </button>
</form>
<button onClick={() => history.push('/product')}> &laquo; back </button>
</>
}
export default Update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment