import { createServerFn } from '@tanstack/react-start' import { createFileRoute, useRouter } from '@tanstack/react-router' import { getClient } from '#/db' const getTodos = createServerFn({ method: 'GET', }).handler(async () => { const client = await getClient() if (!client) { return undefined } return (await client.query(`SELECT * FROM todos`)) as Array<{ id: number title: string }> }) const insertTodo = createServerFn({ method: 'POST', }) .inputValidator((d: { title: string }) => d) .handler(async ({ data }) => { const client = await getClient() if (!client) { return undefined } await client.query(`INSERT INTO todos (title) VALUES ($1)`, [data.title]) }) export const Route = createFileRoute('/demo/neon')({ component: App, loader: async () => { const todos = await getTodos() return { todos } }, }) function App() { const { todos } = Route.useLoaderData() const router = useRouter() const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() const formData = new FormData(e.target as HTMLFormElement) const data = Object.fromEntries(formData) await insertTodo({ data: { title: data.title as string } }) router.invalidate() } if (!todos) { return (
) } return (
Neon Logo

Database

Neon Demo

{todos && ( <>

Todos

    {todos.map((todo: { id: number; title: string }) => (
  • {todo.title} #{todo.id}
  • ))}
)}
) } function DBConnectionError() { return (

Database Connection Issue

The Neon database is not connected.

Required Steps to Fix:

  • 1
    Use the db/init.sql file to create the database
  • 2
    Set the DATABASE_URL environment variable to the connection string of your Neon database
) }