Commit 9d1adcd6 authored by Ben Anderson's avatar Ben Anderson

Added redirect after form submission, connected it to local API

parent 17319145
import React, { useState } from "react"; import React, { useState } from "react";
import { useHistory, useLocation } from "react-router";
const emptyForm = {
sku: "",
upc: "",
productName: "",
brand: "",
category: "",
price: 0.0,
stock: 0,
productDescription: "",
productImage: "",
};
ProductForm.defaultProps = { ProductForm.defaultProps = {
product: { product: { ...emptyForm },
sku: "",
upc: "",
productName: "",
brand: "",
category: "",
price: 0.0,
stock: 0,
productDescription: "",
productImage: "",
},
}; };
export default function ProductForm({ product }) { export default function ProductForm(props) {
const { product } = props;
const [form, setForm] = useState(product); const [form, setForm] = useState(product);
const [errors, setErrors] = useState([]); const [errors, setErrors] = useState([]);
const history = useHistory();
const validate = () => { const validate = () => {
setErrors([]); setErrors([]);
...@@ -52,8 +57,27 @@ export default function ProductForm({ product }) { ...@@ -52,8 +57,27 @@ export default function ProductForm({ product }) {
validate(); validate();
if (errors.length === 0) { if (errors.length === 0) {
// TODO send form to products API // console.log(form);
console.log(form); fetch("http://localhost:8080/api/products", {
method: "POST",
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]);
});
} }
}; };
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment