import React, { ChangeEvent } from 'react';
import { Layout } from '../shared/Layout';
import { CustomerClient } from '../../APIClient';
import Swal from 'sweetalert2';
function Errors({ errors }) {
return errors.map(x => (
{x}
));
}
class CreateCustomer extends React.Component<{}, {
form: {
name: string,
email: string,
},
errors: string[],
busy: boolean,
}> {
constructor(props) {
super(props)
this.state = {
form: {
name: "",
email: "",
},
errors: [],
busy: false,
}
}
onNameChanged(e: ChangeEvent) {
this.setState({
form: {
name: e.target.value,
email: this.state.form.email,
}
});
}
onEmailChanged(e: ChangeEvent) {
this.setState({
form: {
name: this.state.form.name,
email: e.target.value
}
});
}
async validate() {
let errors: string[] = [];
if (!this.state.form.name) {
errors.push("Name required");
}
if (!this.state.form.email) {
errors.push("Email required");
}
await new Promise((resolve) => {
this.setState({
errors
}, () => resolve(undefined));
})
return errors.length == 0;
}
async onSubmit(e) {
e.preventDefault();
if (await this.validate()) {
await new Promise((resolve) => {
this.setState({
busy: true,
}, () => resolve(undefined));
})
try {
const form = this.state.form;
const client = new CustomerClient();
await client.post({
name: form.name,
email: form.email,
})
Swal.fire({
title: "Submitted!",
text: "Customer is now in database",
})
} catch (error) {
} finally {
await new Promise((resolve) => {
this.setState({
busy: false,
}, () => resolve(undefined));
})
}
}
}
render() {
return (
)
}
}
export default function CreateCustomerPage() {
return (
)
}