|
|
|
|
import { component, html, useState } from 'haunted';
|
|
|
|
|
import { spread } from '@open-wc/lit-helpers';
|
|
|
|
|
import { useMutation } from '@apollo/react-hooks';
|
|
|
|
|
import * as yup from 'yup';
|
|
|
|
|
|
|
|
|
|
import { useFormField } from './myhooks';
|
|
|
|
|
import { AddBook, GetBooks } from './queries'
|
|
|
|
|
import Css from './bookform.scss';
|
|
|
|
|
|
|
|
|
|
const schema = yup.object().shape({
|
|
|
|
|
title: yup.string().required(),
|
|
|
|
|
author: yup.string().required(),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const BookForm = () => {
|
|
|
|
|
const [titleProps, setTitle] = useFormField("title");
|
|
|
|
|
const [authorProps, setAuthor] = useFormField("author");
|
|
|
|
|
const [addBook, { loading }] = useMutation(AddBook);
|
|
|
|
|
|
|
|
|
|
return html`
|
|
|
|
|
<style>${Css.toString()}</style>
|
|
|
|
|
<input placeholder="book title" ...=${spread(titleProps)}>
|
|
|
|
|
<input placeholder="author name" ...=${spread(authorProps)}>
|
|
|
|
|
<button @click=${async () => {
|
|
|
|
|
try {
|
|
|
|
|
const newBook = await schema.validate({
|
|
|
|
|
author: authorProps[".value"],
|
|
|
|
|
title: titleProps[".value"]
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
await addBook({
|
|
|
|
|
variables: newBook,
|
|
|
|
|
update: (cache, { data }) => {
|
|
|
|
|
const { books }: any = cache.readQuery({ query: GetBooks });
|
|
|
|
|
cache.writeQuery({ query: GetBooks, data: { books: [...books, data.addBook] }});
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
setTitle("");
|
|
|
|
|
setAuthor("");
|
|
|
|
|
} catch(e) {
|
|
|
|
|
console.log(e);
|
|
|
|
|
if (e instanceof yup.ValidationError) {
|
|
|
|
|
console.log("validation error");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}} ?disabled=${loading}>Add book</button>
|
|
|
|
|
`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
customElements.define('book-form', component(BookForm));
|
|
|
|
|
|