|
| 1 | +import { useCallback, useState } from 'react' |
| 2 | +import { createFileRoute } from '@tanstack/react-router' |
| 3 | +import { useMutation, useQuery } from '@tanstack/react-query' |
| 4 | + |
| 5 | +import { orpc } from '@/orpc/client' |
| 6 | + |
| 7 | +export const Route = createFileRoute('/demo/orpc-todo')({ |
| 8 | + component: ORPCTodos, |
| 9 | + loader: async ({ context }) => { |
| 10 | + await context.queryClient.prefetchQuery( |
| 11 | + orpc.listTodos.queryOptions({ |
| 12 | + input: {}, |
| 13 | + }), |
| 14 | + ) |
| 15 | + }, |
| 16 | +}) |
| 17 | + |
| 18 | +function ORPCTodos() { |
| 19 | + const { data, refetch } = useQuery( |
| 20 | + orpc.listTodos.queryOptions({ |
| 21 | + input: {}, |
| 22 | + }), |
| 23 | + ) |
| 24 | + |
| 25 | + const [todo, setTodo] = useState('') |
| 26 | + const { mutate: addTodo } = useMutation({ |
| 27 | + mutationFn: orpc.addTodo.call, |
| 28 | + onSuccess: () => { |
| 29 | + refetch() |
| 30 | + setTodo('') |
| 31 | + }, |
| 32 | + }) |
| 33 | + |
| 34 | + const submitTodo = useCallback(() => { |
| 35 | + addTodo({ name: todo }) |
| 36 | + }, [addTodo, todo]) |
| 37 | + |
| 38 | + return ( |
| 39 | + <div |
| 40 | + className="flex items-center justify-center min-h-screen bg-gradient-to-br from-purple-100 to-blue-100 p-4 text-white" |
| 41 | + style={{ |
| 42 | + backgroundImage: |
| 43 | + 'radial-gradient(50% 50% at 50% 50%, #D2149D 0%, #8E1066 50%, #2D0A1F 100%)', |
| 44 | + }} |
| 45 | + > |
| 46 | + <div className="w-full max-w-2xl p-8 rounded-xl backdrop-blur-md bg-black/50 shadow-xl border-8 border-black/10"> |
| 47 | + <h1 className="text-2xl mb-4">Todos list</h1> |
| 48 | + <ul className="mb-4 space-y-2"> |
| 49 | + {data?.map((todo) => ( |
| 50 | + <li |
| 51 | + key={todo.id} |
| 52 | + className="bg-white/10 border border-white/20 rounded-lg p-3 backdrop-blur-sm shadow-md" |
| 53 | + > |
| 54 | + <span className="text-lg text-white">{todo.name}</span> |
| 55 | + </li> |
| 56 | + ))} |
| 57 | + </ul> |
| 58 | + <div className="flex flex-col gap-2"> |
| 59 | + <input |
| 60 | + type="text" |
| 61 | + value={todo} |
| 62 | + onChange={(e) => setTodo(e.target.value)} |
| 63 | + onKeyDown={(e) => { |
| 64 | + if (e.key === 'Enter') { |
| 65 | + submitTodo() |
| 66 | + } |
| 67 | + }} |
| 68 | + placeholder="Enter a new todo..." |
| 69 | + className="w-full px-4 py-3 rounded-lg border border-white/20 bg-white/10 backdrop-blur-sm text-white placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent" |
| 70 | + /> |
| 71 | + <button |
| 72 | + disabled={todo.trim().length === 0} |
| 73 | + onClick={submitTodo} |
| 74 | + className="bg-blue-500 hover:bg-blue-600 disabled:bg-blue-500/50 disabled:cursor-not-allowed text-white font-bold py-3 px-4 rounded-lg transition-colors" |
| 75 | + > |
| 76 | + Add todo |
| 77 | + </button> |
| 78 | + </div> |
| 79 | + </div> |
| 80 | + </div> |
| 81 | + ) |
| 82 | +} |
0 commit comments