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 { useHistory, useLocation } from "react-router";
ProductForm.defaultProps = {
product: {
const emptyForm = {
sku: "",
upc: "",
productName: "",
......@@ -11,12 +11,17 @@ ProductForm.defaultProps = {
stock: 0,
productDescription: "",
productImage: "",
},
};
export default function ProductForm({ product }) {
ProductForm.defaultProps = {
product: { ...emptyForm },
};
export default function ProductForm(props) {
const { product } = props;
const [form, setForm] = useState(product);
const [errors, setErrors] = useState([]);
const history = useHistory();
const validate = () => {
setErrors([]);
......@@ -52,8 +57,27 @@ export default function ProductForm({ product }) {
validate();
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