import React, { useEffect, useState } from "react"; import { useHistory, useParams } from "react-router"; import emptyProduct from "../emptProduct"; import Config from "../config"; const emptyForm = { ...emptyProduct, imageFile: "", }; ProductForm.defaultProps = { product: { ...emptyForm }, }; export default function ProductForm(props) { const { method } = props; const [form, setForm] = useState({ ...emptyForm }); const [imageMode, setImageMode] = useState("url"); const [errors, setErrors] = useState([]); const history = useHistory(); const { productId } = useParams("productId"); useEffect(() => { fetch(`${Config.inventoryUrl}/${productId}/`).then((res) => { if (res.ok) { // console.log(res); res.json().then((data) => { Object.keys(data).forEach((key) => { if (data[key] === null) { data[key] = ""; } }); // console.log(data); setForm({ ...data }); }); } }); }, [productId]); const validate = () => { setErrors([]); const errs = []; // console.log(form); if (form.sku.length < 3) { errs.push("SKU must be at least 3 characters"); } if (form.upc.length < 3) { errs.push("UPC must be at least 3 characters"); } if (form.productName.length === 0) { errs.push("Please enter a product name"); } if (form.brand.length === 0) { errs.push("Please enter a brand"); } if (form.category.length === 0) { errs.push("Please specify a category"); } if (Number(form.price) <= 0) { errs.push("Price must be greater than 0"); } if (Number(form.availableStock) <= 0) { errs.push("Stock must be greater than 0"); } setErrors([...errs]); }; const onSubmit = (e) => { e.preventDefault(); validate(); if (imageMode === "url") { delete form.imageFile; } else { delete form.prodImgUrl; } if (errors.length === 0) { // console.log(form); const url = method === "PUT" ? `${Config.inventoryUrl}/${productId}` : `${Config.inventoryUrl}`; fetch(url, { method, headers: { "Content-Type": "application/json", }, body: JSON.stringify(form), }) .then((res) => { if (res.ok) { // res.json().then((data) => console.log(data)); history.push("/products"); } else { setErrors([ "The provided SKU was found on an existing object, please try another", ]); } }) .catch((err) => { setErrors([err.message]); }); } }; return (