add useFormField hook

This commit is contained in:
2020-03-03 15:56:23 +01:00
parent b539d9645b
commit ae6bee329f
4 changed files with 44 additions and 11 deletions
+13 -11
View File
@@ -1,6 +1,9 @@
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';
@@ -10,27 +13,26 @@ const schema = yup.object().shape({
});
const BookForm = () => {
const [title, setTitle] = useState("");
const [author, setAuthor] = useState("");
const [titleProps, setTitle] = useFormField("author");
const [authorProps, setAuthor] = useFormField("author");
const [addBook, { loading }] = useMutation(AddBook);
return html`
<style>${Css.toString()}</style>
<input type="text"
placeholder="book title"
.value=${title}
@change=${(e: any) => setTitle(e.target.value)}>
<input type="text"
placeholder="author name"
.value=${author}
@change=${(e: any) => setAuthor(e.target.value)}>
<input placeholder="book title" ...=${spread(titleProps)}>
<input placeholder="author name" ...=${spread(authorProps)}>
<button @click=${async () => {
try {
const data = await schema.validate({ author, title });
const data = await schema.validate({
author: authorProps[".value"],
title: titleProps[".value"]
});
await addBook({ variables: data, update: (cache, result) => {
const list: any = cache.readQuery({ query: GetBooks });
cache.writeQuery({ query: GetBooks, data: { books: [...list.books, result.data.addBook] }});
}});
setTitle("");
setAuthor("");
} catch(e) {
+25
View File
@@ -0,0 +1,25 @@
import { useState } from 'haunted';
type FormField = [
{
name: string;
type: "text";
'.value': string;
'@change': (e: any) => void;
},
(value: string) => void
];
export const useFormField = (name: string, defaultValue = ""): FormField => {
const [value, setValue] = useState(defaultValue);
const changeHandler = (e: any) => {
setValue(e.target.value);
};
return [
{ name, type: "text", '.value': value, '@change': changeHandler },
setValue
];
};