add useFormField hook
This commit is contained in:
+13
-11
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
];
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user