import React, { ChangeEvent } from 'react';
import { withRouter, NextRouter } from 'next/router';
import { Layout } from '../../shared/Layout';
import { CustomerClient } from '../../../APIClient';
import Swal from 'sweetalert2';
function Errors({ errors }) {
return errors.map(x => (
{x}
));
}
class EditCustomer extends React.Component<{
router: NextRouter,
}, {
form: {
name: string,
email: string,
},
errors: string[],
busy: boolean,
}> {
constructor(props) {
super(props)
const router = props.router;
const { id } = router.query!;
this.state = {
form: {
name: "",
email: "",
},
errors: [],
busy: false,
}
}
async componentDidMount() {
const client = new CustomerClient();
console.log(this.props.router)
if (this.props.router.query['id']) {
let data = await client.get(this.props.router.query['id']);
this.setState({
form: {
name: data.name,
email: data.email,
}
});
}
}
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.put(this.props.router.query.id, {
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 EditCustomerPage() {
let EditCustomerMain = withRouter(EditCustomer);
return (
)
}