Browse Source

Cleaned book form

master
Anthony Hinsinger 6 years ago
parent
commit
ab9f6a2c3a
  1. 39
      src/web/bookform.ts

39
src/web/bookform.ts

@ -1,4 +1,4 @@
import { component, html, useState } from 'haunted'; import { component, html } from 'haunted';
import { spread } from '@open-wc/lit-helpers'; import { spread } from '@open-wc/lit-helpers';
import { useMutation } from '@apollo/react-hooks'; import { useMutation } from '@apollo/react-hooks';
@ -7,22 +7,9 @@ import { AddBook, GetBooks } from './queries'
import Css from './bookform.scss'; import Css from './bookform.scss';
const BookForm = () => { const BookForm = () => {
const [titleProps, titleMeta] = useFormField("title"); const [titleProps, { reset: resetAuthor, isDirty: dirtyAuthor}] = useFormField("title");
const [authorProps, authorMeta] = useFormField("author"); const [authorProps, { reset: resetTitle, isDirty: dirtyTitle}] = useFormField("author");
const [addBook, { loading }] = useMutation(AddBook); const [addBook, { loading }] = useMutation(AddBook, {
return html`
<style>${Css.toString()}</style>
<form @submit=${async (e: Event) => {
e.preventDefault();
try {
const newBook = {
author: authorProps[".value"],
title: titleProps[".value"]
};
await addBook({
variables: newBook,
update: (cache, { data }) => { update: (cache, { data }) => {
const { books }: any = cache.readQuery({ query: GetBooks }); const { books }: any = cache.readQuery({ query: GetBooks });
cache.writeQuery({ cache.writeQuery({
@ -32,20 +19,30 @@ const BookForm = () => {
} }
}); });
titleMeta.reset(); return html`
authorMeta.reset(); <style>${Css.toString()}</style>
<form @submit=${async (e: Event) => {
e.preventDefault();
try {
await addBook({ variables: {
author: authorProps[".value"],
title: titleProps[".value"]
}});
resetAuthor();
resetTitle();
} catch(e) { } catch(e) {
console.log(e); console.log(e);
} }
}}> }}>
<input <input
required required
class=${titleMeta.isDirty ? "dirty" : ""} class=${dirtyAuthor ? "dirty" : ""}
placeholder="book title" placeholder="book title"
...=${spread(titleProps)}> ...=${spread(titleProps)}>
<input <input
required required
class=${authorMeta.isDirty ? "dirty" : ""} class=${dirtyTitle ? "dirty" : ""}
placeholder="author name" placeholder="author name"
...=${spread(authorProps)}> ...=${spread(authorProps)}>
<button ?disabled=${loading}>+ Add book</button> <button ?disabled=${loading}>+ Add book</button>

Loading…
Cancel
Save