|
1 |
| -import { createSignal, JSX } from "solid-js"; |
| 1 | +import { createResource, createSignal } from "solid-js"; |
| 2 | +import { For, Show } from "solid-js/web"; |
| 3 | +import { searchBooks } from "./utils/searchBooks"; |
2 | 4 |
|
3 | 5 | import type { Setter } from "solid-js";
|
4 | 6 | import type { Book } from "./App";
|
| 7 | + |
5 | 8 | export interface IAddBookProps {
|
6 | 9 | setBooks: Setter<Book[]>;
|
7 | 10 | }
|
8 | 11 |
|
9 | 12 | const emptyBook: Book = { title: "", author: "" };
|
10 | 13 |
|
11 | 14 | export default function AddBook(props: IAddBookProps) {
|
12 |
| - const [newBook, setNewBook] = createSignal(emptyBook); |
13 |
| - const addBook: JSX.EventHandler<HTMLButtonElement, MouseEvent> = (event) => { |
14 |
| - event.preventDefault(); |
15 |
| - props.setBooks((books) => [...books, newBook()]); |
16 |
| - setNewBook(emptyBook); |
17 |
| - }; |
| 15 | + const [input, setInput] = createSignal(""); |
| 16 | + const [query, setQuery] = createSignal(""); |
| 17 | + const [data] = createResource<Array<Book>, string>(query, searchBooks); |
| 18 | + |
18 | 19 | return (
|
19 |
| - <form> |
20 |
| - <div> |
21 |
| - <label for="title">Book name</label> |
22 |
| - <input |
23 |
| - id="title" |
24 |
| - value={newBook().title} |
25 |
| - onInput={(e) => { |
26 |
| - setNewBook({ ...newBook(), title: e.currentTarget.value }); |
27 |
| - }} |
28 |
| - /> |
29 |
| - </div> |
30 |
| - <br /> |
31 |
| - <div> |
32 |
| - <label for="author">Author</label> |
33 |
| - <input |
34 |
| - id="author" |
35 |
| - value={newBook().author} |
36 |
| - onInput={(e) => { |
37 |
| - setNewBook({ ...newBook(), author: e.currentTarget.value }); |
| 20 | + <> |
| 21 | + <form> |
| 22 | + <div> |
| 23 | + <label for="title">Search books</label> |
| 24 | + <input |
| 25 | + id="title" |
| 26 | + value={input()} |
| 27 | + onInput={(e) => { |
| 28 | + setInput(e.currentTarget.value); |
| 29 | + }} |
| 30 | + /> |
| 31 | + </div> |
| 32 | + <button |
| 33 | + type="submit" |
| 34 | + onClick={(e) => { |
| 35 | + e.preventDefault(); |
| 36 | + setQuery(input()); |
38 | 37 | }}
|
39 |
| - /> |
40 |
| - </div> |
41 |
| - <button type="submit" onClick={addBook}> |
42 |
| - Add book |
43 |
| - </button> |
44 |
| - </form> |
| 38 | + > |
| 39 | + Search |
| 40 | + </button> |
| 41 | + </form> |
| 42 | + <Show when={!data.loading} fallback={<>Searching...</>}> |
| 43 | + <ul> |
| 44 | + <For each={data()}> |
| 45 | + {(book) => ( |
| 46 | + <li> |
| 47 | + {book.title} by {book.author}{" "} |
| 48 | + <button |
| 49 | + aria-label={`Add ${book.title} by ${book.author} to the bookshelf`} |
| 50 | + onClick={(e) => { |
| 51 | + e.preventDefault(); |
| 52 | + props.setBooks((books) => [...books, book]); |
| 53 | + }} |
| 54 | + > |
| 55 | + Add |
| 56 | + </button> |
| 57 | + </li> |
| 58 | + )} |
| 59 | + </For> |
| 60 | + </ul> |
| 61 | + </Show> |
| 62 | + </> |
45 | 63 | );
|
46 | 64 | }
|
0 commit comments