ASPNetCore/Next/pages/product/create.tsx

72 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-03-29 07:40:58 +00:00
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
2021-03-29 07:08:26 +00:00
import { Layout } from '../shared/Layout';
import { ProductClient } from '../../APIClient';
import Swal from 'sweetalert2';
import ProductForm from '../../components/ProductForm';
import Link from 'next/link';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons';
2021-03-29 07:40:58 +00:00
import { validateForm } from '../../lib/product';
2021-03-29 07:08:26 +00:00
2021-03-29 07:40:58 +00:00
function Errors({ errors }) {
return errors.map(x => (
<li>{x}</li>
));
}
function CreateProduct() {
let [form, setForm] = useState({ name: "", price: 0 });
let [busy, setBusy] = useState(false);
2021-03-29 09:53:55 +00:00
let [errors, setErrors] = useState([""]);
2021-03-29 07:40:58 +00:00
2021-03-29 09:53:55 +00:00
const onFormChanged = (form) => {
setForm(form);
2021-03-29 07:08:26 +00:00
}
2021-03-29 07:40:58 +00:00
const onSubmit = async () => {
2021-03-29 09:53:55 +00:00
setBusy(true);
try {
const client = new ProductClient();
await client.post({
name: form.name,
price: form.price,
})
Swal.fire({
title: "Submitted!",
text: "Product is added in database",
})
} catch (error) {
2021-03-29 07:08:26 +00:00
2021-03-29 09:53:55 +00:00
} finally {
setBusy(false);
2021-03-29 07:08:26 +00:00
}
}
2021-03-29 07:40:58 +00:00
return (
<div className="container mx-auto">
<h1>Create Product</h1>
<Link href="/product/">
<a>
<FontAwesomeIcon icon={faArrowLeft} /> Return to index
2021-03-29 07:08:26 +00:00
</a>
2021-03-29 07:40:58 +00:00
</Link>
<ProductForm
name={form.name}
price={form.price}
busy={busy}
2021-03-29 09:53:55 +00:00
onFormChange={onFormChanged}
2021-03-29 07:40:58 +00:00
onSubmit={onSubmit} />
<ul>
<Errors errors={errors}></Errors>
</ul>
</div>
);
2021-03-29 07:08:26 +00:00
}
export default function CreateProductPage() {
return (
<Layout title="Create product">
<CreateProduct></CreateProduct>
</Layout>
)
}