|
| 1 | +import { NextPage } from "next"; |
| 2 | +import Head from "next/head"; |
| 3 | +import { useMemo, useState } from "react"; |
| 4 | +import { createTodo, deleteTodo, toggleTodo, useTodos } from "../api"; |
| 5 | +import styles from "../styles/Home.module.css"; |
| 6 | +import { Todo } from "../types"; |
| 7 | + |
| 8 | +export const TodoList: React.FC = () => { |
| 9 | + const { data: todos, error } = useTodos(); |
| 10 | + |
| 11 | + if (error != null) return <div>Error loading todos...</div>; |
| 12 | + if (todos == null) return <div>Loading...</div>; |
| 13 | + |
| 14 | + if (todos.length === 0) { |
| 15 | + return <div className={styles.emptyState}>Try adding a todo ☝️️</div>; |
| 16 | + } |
| 17 | + |
| 18 | + return ( |
| 19 | + <ul className={styles.todoList}> |
| 20 | + {todos.map(todo => ( |
| 21 | + <TodoItem todo={todo} /> |
| 22 | + ))} |
| 23 | + </ul> |
| 24 | + ); |
| 25 | +}; |
| 26 | + |
| 27 | +const TodoItem: React.FC<{ todo: Todo }> = ({ todo }) => ( |
| 28 | + <li className={styles.todo}> |
| 29 | + <label |
| 30 | + className={`${styles.label} ${todo.completed ? styles.checked : ""}`} |
| 31 | + > |
| 32 | + <input |
| 33 | + type="checkbox" |
| 34 | + checked={todo.completed} |
| 35 | + className={`${styles.checkbox}`} |
| 36 | + onChange={() => toggleTodo(todo)} |
| 37 | + /> |
| 38 | + {todo.text} |
| 39 | + </label> |
| 40 | + |
| 41 | + <button className={styles.deleteButton} onClick={() => deleteTodo(todo.id)}> |
| 42 | + ✕ |
| 43 | + </button> |
| 44 | + </li> |
| 45 | +); |
| 46 | + |
| 47 | +const AddTodoInput = () => { |
| 48 | + const [text, setText] = useState(""); |
| 49 | + |
| 50 | + return ( |
| 51 | + <form |
| 52 | + onSubmit={async e => { |
| 53 | + e.preventDefault(); |
| 54 | + createTodo(text); |
| 55 | + setText(""); |
| 56 | + }} |
| 57 | + className={styles.addTodo} |
| 58 | + > |
| 59 | + <input |
| 60 | + className={styles.input} |
| 61 | + placeholder="Buy some milk" |
| 62 | + value={text} |
| 63 | + onChange={e => setText(e.target.value)} |
| 64 | + /> |
| 65 | + <button className={styles.addButton}>Add</button> |
| 66 | + </form> |
| 67 | + ); |
| 68 | +}; |
| 69 | + |
| 70 | +const Home: NextPage = () => { |
| 71 | + return ( |
| 72 | + <div className={styles.container}> |
| 73 | + <Head> |
| 74 | + <title>Railway NextJS Prisma</title> |
| 75 | + <link rel="icon" href="/favicon.ico" /> |
| 76 | + </Head> |
| 77 | + |
| 78 | + <header className={styles.header}> |
| 79 | + <h1 className={styles.title}>Todos</h1> |
| 80 | + <h2 className={styles.desc}> |
| 81 | + NextJS app connected to Postgres using Prisma and hosted on{" "} |
| 82 | + <a href="https://railway.app">Railway</a> |
| 83 | + </h2> |
| 84 | + </header> |
| 85 | + |
| 86 | + <main className={styles.main}> |
| 87 | + <AddTodoInput /> |
| 88 | + |
| 89 | + <TodoList /> |
| 90 | + </main> |
| 91 | + </div> |
| 92 | + ); |
| 93 | +}; |
| 94 | + |
| 95 | +export default Home; |
0 commit comments