add convex

This commit is contained in:
Aman Varshney
2025-04-28 11:42:11 +05:30
parent 7ef3cfce9e
commit 2a5358a105
70 changed files with 2330 additions and 1139 deletions

View File

@@ -16,7 +16,12 @@
"dev": {
"cache": false,
"persistent": true
},
}{{#if (eq backend "convex")}},
"setup": {
"cache": false,
"persistent": true
}
{{else}}{{#unless (or (eq database "none") (eq orm "none"))}},
"db:push": {
"cache": false,
"persistent": true
@@ -25,5 +30,6 @@
"cache": false,
"persistent": true
}
{{/unless}}{{/if}}
}
}

View File

@@ -92,8 +92,6 @@ export async function createContext(opts: any) {
}
{{else}}
// Default or fallback context if backend is not recognized or none
// This might need adjustment based on your default behavior
export async function createContext() {
return {
session: null,

View File

@@ -1,6 +1,5 @@
<script setup lang="ts">
import { z } from 'zod'
// import { authClient } from "~/lib/auth-client";
const {$authClient} = useNuxtApp()
import type { FormSubmitEvent } from '#ui/types'

View File

@@ -1,7 +1,6 @@
<script setup lang="ts">
import { z } from 'zod'
import type { FormSubmitEvent } from '#ui/types'
// import { authClient } from "~/lib/auth-client";
const {$authClient} = useNuxtApp()
const emit = defineEmits(['switchToSignIn'])

View File

@@ -1,6 +1,5 @@
<script setup lang="ts">
// import { authClient } from "~/lib/auth-client";
const {$authClient} = useNuxtApp()
const session = $authClient.useSession()
const toast = useToast()

View File

@@ -0,0 +1,2 @@
.env.local

View File

@@ -0,0 +1,90 @@
# Welcome to your Convex functions directory!
Write your Convex functions here.
See https://docs.convex.dev/functions for more.
A query function that takes two arguments looks like:
```ts
// functions.js
import { query } from "./_generated/server";
import { v } from "convex/values";
export const myQueryFunction = query({
// Validators for arguments.
args: {
first: v.number(),
second: v.string(),
},
// Function implementation.
handler: async (ctx, args) => {
// Read the database as many times as you need here.
// See https://docs.convex.dev/database/reading-data.
const documents = await ctx.db.query("tablename").collect();
// Arguments passed from the client are properties of the args object.
console.log(args.first, args.second);
// Write arbitrary JavaScript here: filter, aggregate, build derived data,
// remove non-public properties, or create new objects.
return documents;
},
});
```
Using this query function in a React component looks like:
```ts
const data = useQuery(api.functions.myQueryFunction, {
first: 10,
second: "hello",
});
```
A mutation function looks like:
```ts
// functions.js
import { mutation } from "./_generated/server";
import { v } from "convex/values";
export const myMutationFunction = mutation({
// Validators for arguments.
args: {
first: v.string(),
second: v.string(),
},
// Function implementation.
handler: async (ctx, args) => {
// Insert or modify documents in the database here.
// Mutations can also read from the database like queries.
// See https://docs.convex.dev/database/writing-data.
const message = { body: args.first, author: args.second };
const id = await ctx.db.insert("messages", message);
// Optionally, return a value from your mutation.
return await ctx.db.get(id);
},
});
```
Using this mutation function in a React component looks like:
```ts
const mutation = useMutation(api.functions.myMutationFunction);
function handleButtonPress() {
// fire and forget, the most common way to use mutations
mutation({ first: "Hello!", second: "me" });
// OR
// use the result once the mutation has completed
mutation({ first: "Hello!", second: "me" }).then((result) =>
console.log(result),
);
}
```
Use the Convex CLI to push your functions to a deployment. See everything
the Convex CLI can do by running `npx convex -h` in your project root
directory. To learn more, launch the docs with `npx convex docs`.

View File

@@ -0,0 +1,7 @@
import { query } from "./_generated/server";
export const get = query({
handler: async () => {
return "OK";
}
})

View File

@@ -0,0 +1,9 @@
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
export default defineSchema({
todos: defineTable({
text: v.string(),
completed: v.boolean(),
}),
});

View File

@@ -0,0 +1,42 @@
import { query, mutation } from "./_generated/server";
import { v } from "convex/values";
export const getAll = query({
handler: async (ctx) => {
return await ctx.db.query("todos").collect();
},
});
export const create = mutation({
args: {
text: v.string(),
},
handler: async (ctx, args) => {
const newTodoId = await ctx.db.insert("todos", {
text: args.text,
completed: false,
});
return await ctx.db.get(newTodoId);
},
});
export const toggle = mutation({
args: {
id: v.id("todos"),
completed: v.boolean(),
},
handler: async (ctx, args) => {
await ctx.db.patch(args.id, { completed: args.completed });
return { success: true };
},
});
export const deleteTodo = mutation({
args: {
id: v.id("todos"),
},
handler: async (ctx, args) => {
await ctx.db.delete(args.id);
return { success: true };
},
});

View File

@@ -0,0 +1,25 @@
{
/* This TypeScript project config describes the environment that
* Convex functions run in and is used to typecheck them.
* You can modify it, but some settings required to use Convex.
*/
"compilerOptions": {
/* These settings are not required by Convex and can be modified. */
"allowJs": true,
"strict": true,
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
/* These compiler options are required by Convex */
"target": "ESNext",
"lib": ["ES2021", "dom"],
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"isolatedModules": true,
"noEmit": true
},
"include": ["./**/*"],
"exclude": ["./_generated"]
}

View File

@@ -0,0 +1,21 @@
{
"name": "@{{projectName}}/backend",
"version": "1.0.0",
"private": true,
"exports": {
"./convex/*": "./convex/*"
},
"scripts": {
"dev": "convex dev",
"setup": "convex dev --until-success"
},
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"typescript": "^5.8.3"
},
"dependencies": {
"convex": "^1.23.0"
}
}

View File

@@ -2,7 +2,8 @@
"name": "better-t-stack",
"private": true,
"workspaces": [
"apps/*"
"apps/*",
"packages/*"
],
"scripts": {

View File

@@ -8,61 +8,90 @@ import {
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { trpc } from "@/utils/trpc";
{{/if}}
import { useMutation, useQuery } from "@tanstack/react-query";
import { Loader2, Trash2 } from "lucide-react";
import { useState } from "react";
{{#if (eq backend "convex")}}
import { useMutation, useQuery } from "convex/react";
import { api } from "@{{projectName}}/backend/convex/_generated/api.js";
import type { Id } from "@{{projectName}}/backend/convex/_generated/dataModel.d.ts";
{{else}}
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { trpc } from "@/utils/trpc";
{{/if}}
import { useMutation, useQuery } from "@tanstack/react-query";
{{/if}}
export default function Todos() {
const [newTodoText, setNewTodoText] = useState("");
{{#if (eq api "orpc")}}
const todos = useQuery(orpc.todo.getAll.queryOptions());
const createMutation = useMutation(
orpc.todo.create.mutationOptions({
onSuccess: () => {
todos.refetch();
setNewTodoText("");
},
})
);
const toggleMutation = useMutation(
orpc.todo.toggle.mutationOptions({
onSuccess: () => todos.refetch(),
})
);
const deleteMutation = useMutation(
orpc.todo.delete.mutationOptions({
onSuccess: () => todos.refetch(),
})
);
{{/if}}
{{#if (eq api "trpc")}}
const todos = useQuery(trpc.todo.getAll.queryOptions());
const createMutation = useMutation(
trpc.todo.create.mutationOptions({
onSuccess: () => {
todos.refetch();
setNewTodoText("");
},
})
);
const toggleMutation = useMutation(
trpc.todo.toggle.mutationOptions({
onSuccess: () => todos.refetch(),
})
);
const deleteMutation = useMutation(
trpc.todo.delete.mutationOptions({
onSuccess: () => todos.refetch(),
})
);
{{/if}}
{{#if (eq backend "convex")}}
const todos = useQuery(api.todos.getAll);
const createTodo = useMutation(api.todos.create);
const toggleTodo = useMutation(api.todos.toggle);
const deleteTodo = useMutation(api.todos.deleteTodo);
const handleAddTodo = async (e: React.FormEvent) => {
e.preventDefault();
const text = newTodoText.trim();
if (!text) return;
await createTodo({ text });
setNewTodoText("");
};
const handleToggleTodo = (id: Id<"todos">, currentCompleted: boolean) => {
toggleTodo({ id, completed: !currentCompleted });
};
const handleDeleteTodo = (id: Id<"todos">) => {
deleteTodo({ id });
};
{{else}}
{{#if (eq api "orpc")}}
const todos = useQuery(orpc.todo.getAll.queryOptions());
const createMutation = useMutation(
orpc.todo.create.mutationOptions({
onSuccess: () => {
todos.refetch();
setNewTodoText("");
},
})
);
const toggleMutation = useMutation(
orpc.todo.toggle.mutationOptions({
onSuccess: () => todos.refetch(),
})
);
const deleteMutation = useMutation(
orpc.todo.delete.mutationOptions({
onSuccess: () => todos.refetch(),
})
);
{{/if}}
{{#if (eq api "trpc")}}
const todos = useQuery(trpc.todo.getAll.queryOptions());
const createMutation = useMutation(
trpc.todo.create.mutationOptions({
onSuccess: () => {
todos.refetch();
setNewTodoText("");
},
})
);
const toggleMutation = useMutation(
trpc.todo.toggle.mutationOptions({
onSuccess: () => todos.refetch(),
})
);
const deleteMutation = useMutation(
trpc.todo.delete.mutationOptions({
onSuccess: () => todos.refetch(),
})
);
{{/if}}
const handleAddTodo = (e: React.FormEvent) => {
e.preventDefault();
@@ -78,6 +107,7 @@ export default function Todos() {
const handleDeleteTodo = (id: number) => {
deleteMutation.mutate({ id });
};
{{/if}}
return (
<div className="w-full mx-auto max-w-md py-10">
@@ -95,62 +125,117 @@ export default function Todos() {
value={newTodoText}
onChange={(e) => setNewTodoText(e.target.value)}
placeholder="Add a new task..."
{{#if (eq backend "convex")}}
{{!-- Convex mutations don't have an easy isPending state here, disable based on text --}}
{{else}}
disabled={createMutation.isPending}
{{/if}}
/>
<Button
type="submit"
{{#if (eq backend "convex")}}
disabled={!newTodoText.trim()}
{{else}}
disabled={createMutation.isPending || !newTodoText.trim()}
{{/if}}
>
{createMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
"Add"
)}
{{#if (eq backend "convex")}}
Add
{{else}}
{createMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
"Add"
)}
{{/if}}
</Button>
</form>
{todos.isLoading ? (
<div className="flex justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : todos.data?.length === 0 ? (
<p className="py-4 text-center">
No todos yet. Add one above!
</p>
) : (
<ul className="space-y-2">
{todos.data?.map((todo) => (
<li
key={todo.id}
className="flex items-center justify-between rounded-md border p-2"
>
<div className="flex items-center space-x-2">
<Checkbox
checked={todo.completed}
onCheckedChange={() =>
handleToggleTodo(todo.id, todo.completed)
}
id={`todo-${todo.id}`}
/>
<label
htmlFor={`todo-${todo.id}`}
className={`${todo.completed ? "line-through" : ""}`}
>
{todo.text}
</label>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteTodo(todo.id)}
aria-label="Delete todo"
{{#if (eq backend "convex")}}
{todos === undefined ? (
<div className="flex justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : todos.length === 0 ? (
<p className="py-4 text-center">No todos yet. Add one above!</p>
) : (
<ul className="space-y-2">
{todos.map((todo) => (
<li
key={todo._id}
className="flex items-center justify-between rounded-md border p-2"
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
)}
<div className="flex items-center space-x-2">
<Checkbox
checked={todo.completed}
onCheckedChange={() =>
handleToggleTodo(todo._id, todo.completed)
}
id={`todo-${todo._id}`}
/>
<label
htmlFor={`todo-${todo._id}`}
className={`${todo.completed ? "line-through text-muted-foreground" : ""}`}
>
{todo.text}
</label>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteTodo(todo._id)}
aria-label="Delete todo"
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
)}
{{else}}
{todos.isLoading ? (
<div className="flex justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : todos.data?.length === 0 ? (
<p className="py-4 text-center">
No todos yet. Add one above!
</p>
) : (
<ul className="space-y-2">
{todos.data?.map((todo) => (
<li
key={todo.id}
className="flex items-center justify-between rounded-md border p-2"
>
<div className="flex items-center space-x-2">
<Checkbox
checked={todo.completed}
onCheckedChange={() =>
handleToggleTodo(todo.id, todo.completed)
}
id={`todo-${todo.id}`}
/>
<label
htmlFor={`todo-${todo.id}`}
className={`${todo.completed ? "line-through" : ""}`}
>
{todo.text}
</label>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteTodo(todo.id)}
aria-label="Delete todo"
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
)}
{{/if}}
</CardContent>
</Card>
</div>

View File

@@ -8,17 +8,24 @@ import {
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { trpc } from "@/utils/trpc";
{{/if}}
import { useMutation, useQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import { Loader2, Trash2 } from "lucide-react";
import { useState } from "react";
{{#if (eq backend "convex")}}
import { useMutation, useQuery } from "convex/react";
import { api } from "@{{projectName}}/backend/convex/_generated/api.js";
import type { Id } from "@{{projectName}}/backend/convex/_generated/dataModel.d.ts";
{{else}}
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { trpc } from "@/utils/trpc";
{{/if}}
import { useMutation, useQuery } from "@tanstack/react-query";
{{/if}}
export const Route = createFileRoute("/todos")({
component: TodosRoute,
});
@@ -26,48 +33,70 @@ export const Route = createFileRoute("/todos")({
function TodosRoute() {
const [newTodoText, setNewTodoText] = useState("");
{{#if (eq api "orpc")}}
const todos = useQuery(orpc.todo.getAll.queryOptions());
const createMutation = useMutation(
orpc.todo.create.mutationOptions({
onSuccess: () => {
todos.refetch();
setNewTodoText("");
},
}),
);
const toggleMutation = useMutation(
orpc.todo.toggle.mutationOptions({
onSuccess: () => todos.refetch(),
}),
);
const deleteMutation = useMutation(
orpc.todo.delete.mutationOptions({
onSuccess: () => todos.refetch(),
}),
);
{{/if}}
{{#if (eq api "trpc")}}
const todos = useQuery(trpc.todo.getAll.queryOptions());
const createMutation = useMutation(
trpc.todo.create.mutationOptions({
onSuccess: () => {
todos.refetch();
setNewTodoText("");
},
}),
);
const toggleMutation = useMutation(
trpc.todo.toggle.mutationOptions({
onSuccess: () => todos.refetch(),
}),
);
const deleteMutation = useMutation(
trpc.todo.delete.mutationOptions({
onSuccess: () => todos.refetch(),
}),
);
{{/if}}
{{#if (eq backend "convex")}}
const todos = useQuery(api.todos.getAll);
const createTodo = useMutation(api.todos.create);
const toggleTodo = useMutation(api.todos.toggle);
const deleteTodo = useMutation(api.todos.deleteTodo);
const handleAddTodo = async (e: React.FormEvent) => {
e.preventDefault();
const text = newTodoText.trim();
if (!text) return;
await createTodo({ text });
setNewTodoText("");
};
const handleToggleTodo = (id: Id<"todos">, currentCompleted: boolean) => {
toggleTodo({ id, completed: !currentCompleted });
};
const handleDeleteTodo = (id: Id<"todos">) => {
deleteTodo({ id });
};
{{else}}
{{#if (eq api "orpc")}}
const todos = useQuery(orpc.todo.getAll.queryOptions());
const createMutation = useMutation(
orpc.todo.create.mutationOptions({
onSuccess: () => {
todos.refetch();
setNewTodoText("");
},
}),
);
const toggleMutation = useMutation(
orpc.todo.toggle.mutationOptions({
onSuccess: () => todos.refetch(),
}),
);
const deleteMutation = useMutation(
orpc.todo.delete.mutationOptions({
onSuccess: () => todos.refetch(),
}),
);
{{/if}}
{{#if (eq api "trpc")}}
const todos = useQuery(trpc.todo.getAll.queryOptions());
const createMutation = useMutation(
trpc.todo.create.mutationOptions({
onSuccess: () => {
todos.refetch();
setNewTodoText("");
},
}),
);
const toggleMutation = useMutation(
trpc.todo.toggle.mutationOptions({
onSuccess: () => todos.refetch(),
}),
);
const deleteMutation = useMutation(
trpc.todo.delete.mutationOptions({
onSuccess: () => todos.refetch(),
}),
);
{{/if}}
const handleAddTodo = (e: React.FormEvent) => {
e.preventDefault();
@@ -83,6 +112,7 @@ function TodosRoute() {
const handleDeleteTodo = (id: number) => {
deleteMutation.mutate({ id });
};
{{/if}}
return (
<div className="mx-auto w-full max-w-md py-10">
@@ -100,60 +130,116 @@ function TodosRoute() {
value={newTodoText}
onChange={(e) => setNewTodoText(e.target.value)}
placeholder="Add a new task..."
{{#if (eq backend "convex")}}
{{else}}
disabled={createMutation.isPending}
{{/if}}
/>
<Button
type="submit"
{{#if (eq backend "convex")}}
disabled={!newTodoText.trim()}
{{else}}
disabled={createMutation.isPending || !newTodoText.trim()}
{{/if}}
>
{createMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
"Add"
)}
{{#if (eq backend "convex")}}
Add
{{else}}
{createMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
"Add"
)}
{{/if}}
</Button>
</form>
{todos.isLoading ? (
<div className="flex justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : todos.data?.length === 0 ? (
<p className="py-4 text-center">No todos yet. Add one above!</p>
) : (
<ul className="space-y-2">
{todos.data?.map((todo) => (
<li
key={todo.id}
className="flex items-center justify-between rounded-md border p-2"
>
<div className="flex items-center space-x-2">
<Checkbox
checked={todo.completed}
onCheckedChange={() =>
handleToggleTodo(todo.id, todo.completed)
}
id={`todo-${todo.id}`}
/>
<label
htmlFor={`todo-${todo.id}`}
className={`${todo.completed ? "line-through" : ""}`}
>
{todo.text}
</label>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteTodo(todo.id)}
aria-label="Delete todo"
{{#if (eq backend "convex")}}
{todos === undefined ? (
<div className="flex justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : todos.length === 0 ? (
<p className="py-4 text-center">No todos yet. Add one above!</p>
) : (
<ul className="space-y-2">
{todos.map((todo) => (
<li
key={todo._id}
className="flex items-center justify-between rounded-md border p-2"
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
)}
<div className="flex items-center space-x-2">
<Checkbox
checked={todo.completed}
onCheckedChange={() =>
handleToggleTodo(todo._id, todo.completed)
}
id={`todo-${todo._id}`}
/>
<label
htmlFor={`todo-${todo._id}`}
className={`${todo.completed ? "line-through text-muted-foreground" : ""}`}
>
{todo.text}
</label>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteTodo(todo._id)}
aria-label="Delete todo"
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
)}
{{else}}
{todos.isLoading ? (
<div className="flex justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : todos.data?.length === 0 ? (
<p className="py-4 text-center">
No todos yet. Add one above!
</p>
) : (
<ul className="space-y-2">
{todos.data?.map((todo) => (
<li
key={todo.id}
className="flex items-center justify-between rounded-md border p-2"
>
<div className="flex items-center space-x-2">
<Checkbox
checked={todo.completed}
onCheckedChange={() =>
handleToggleTodo(todo.id, todo.completed)
}
id={`todo-${todo.id}`}
/>
<label
htmlFor={`todo-${todo.id}`}
className={`${todo.completed ? "line-through" : ""}`}
>
{todo.text}
</label>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteTodo(todo.id)}
aria-label="Delete todo"
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
)}
{{/if}}
</CardContent>
</Card>
</div>

View File

@@ -8,32 +8,79 @@ import {
} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
{{#if (eq api "trpc")}}
import { useTRPC } from "@/utils/trpc";
{{/if}}
{{#if (eq api "orpc")}}
import { useORPC } from "@/utils/orpc";
{{/if}}
import { useMutation, useQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import { Loader2, Trash2 } from "lucide-react";
import { useState } from "react";
{{#if (eq backend "convex")}}
import { useSuspenseQuery } from "@tanstack/react-query";
import { convexQuery } from "@convex-dev/react-query";
import { useMutation } from "convex/react";
import { api } from "@{{projectName}}/backend/convex/_generated/api.js";
import type { Id } from "@{{projectName}}/backend/convex/_generated/dataModel.js";
{{else}}
{{#if (eq api "trpc")}}
import { useTRPC } from "@/utils/trpc";
{{/if}}
{{#if (eq api "orpc")}}
import { useORPC } from "@/utils/orpc";
{{/if}}
import { useMutation, useQuery } from "@tanstack/react-query";
{{/if}}
export const Route = createFileRoute("/todos")({
component: TodosRoute,
});
function TodosRoute() {
{{#if (eq api "trpc")}}
const trpc = useTRPC();
{{/if}}
{{#if (eq api "orpc")}}
const orpc = useORPC();
{{/if}}
const [newTodoText, setNewTodoText] = useState("");
{{#if (eq api "trpc")}}
{{#if (eq backend "convex")}}
const todosQuery = useSuspenseQuery(convexQuery(api.todos.getAll, {}));
const todos = todosQuery.data;
const createTodo = useMutation(api.todos.create);
const toggleTodo = useMutation(api.todos.toggle);
const removeTodo = useMutation(api.todos.deleteTodo);
const handleAddTodo = async (e: React.FormEvent) => {
e.preventDefault();
const text = newTodoText.trim();
if (text) {
setNewTodoText("");
try {
await createTodo({ text });
} catch (error) {
console.error("Failed to add todo:", error);
setNewTodoText(text);
}
}
};
const handleToggleTodo = async (id: Id<"todos">, completed: boolean) => {
try {
await toggleTodo({ id, completed: !completed });
} catch (error) {
console.error("Failed to toggle todo:", error);
}
};
const handleDeleteTodo = async (id: Id<"todos">) => {
try {
await removeTodo({ id });
} catch (error) {
console.error("Failed to delete todo:", error);
}
};
{{else}}
{{#if (eq api "trpc")}}
const trpc = useTRPC();
{{/if}}
{{#if (eq api "orpc")}}
const orpc = useORPC();
{{/if}}
{{#if (eq api "trpc")}}
const todos = useQuery(trpc.todo.getAll.queryOptions());
const createMutation = useMutation(
trpc.todo.create.mutationOptions({
@@ -53,8 +100,8 @@ function TodosRoute() {
onSuccess: () => todos.refetch(),
}),
);
{{/if}}
{{#if (eq api "orpc")}}
{{/if}}
{{#if (eq api "orpc")}}
const todos = useQuery(orpc.todo.getAll.queryOptions());
const createMutation = useMutation(
orpc.todo.create.mutationOptions({
@@ -74,7 +121,7 @@ function TodosRoute() {
onSuccess: () => todos.refetch(),
}),
);
{{/if}}
{{/if}}
const handleAddTodo = (e: React.FormEvent) => {
e.preventDefault();
@@ -90,12 +137,13 @@ function TodosRoute() {
const handleDeleteTodo = (id: number) => {
deleteMutation.mutate({ id });
};
{{/if}}
return (
<div className="mx-auto w-full max-w-md py-10">
<Card>
<CardHeader>
<CardTitle>Todo List</CardTitle>
<CardTitle>Todo List{{#if (eq backend "convex")}} (Convex){{/if}}</CardTitle>
<CardDescription>Manage your tasks efficiently</CardDescription>
</CardHeader>
<CardContent>
@@ -107,20 +155,72 @@ function TodosRoute() {
value={newTodoText}
onChange={(e) => setNewTodoText(e.target.value)}
placeholder="Add a new task..."
{{#unless (eq backend "convex")}}
disabled={createMutation.isPending}
{{/unless}}
/>
<Button
type="submit"
{{#unless (eq backend "convex")}}
disabled={createMutation.isPending || !newTodoText.trim()}
{{else}}
disabled={!newTodoText.trim()}
{{/unless}}
>
{{#unless (eq backend "convex")}}
{createMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
"Add"
)}
{{else}}
Add
{{/unless}}
</Button>
</form>
{{#if (eq backend "convex")}}
{todos?.length === 0 ? (
<p className="py-4 text-center">No todos yet. Add one above!</p>
) : (
<ul className="space-y-2">
{todos?.map((todo) => (
<li
key={todo._id}
className="flex items-center justify-between rounded-md border p-2"
>
<div className="flex items-center space-x-2">
<Checkbox
checked={todo.completed}
onCheckedChange={() =>
handleToggleTodo(todo._id, todo.completed)
}
id={`todo-${todo._id}`}
/>
<label
htmlFor={`todo-${todo._id}`}
className={`${
todo.completed
? "text-muted-foreground line-through"
: ""
}`}
>
{todo.text}
</label>
</div>
<Button
variant="ghost"
size="icon"
onClick={() => handleDeleteTodo(todo._id)}
aria-label="Delete todo"
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
)}
{{else}}
{todos.isLoading ? (
<div className="flex justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin" />
@@ -161,6 +261,7 @@ function TodosRoute() {
))}
</ul>
)}
{{/if}}
</CardContent>
</Card>
</div>

View File

@@ -1,2 +1,3 @@
packages:
- "apps/*"
- "packages/*"

View File

@@ -1,12 +1,17 @@
import { useQuery } from "@tanstack/react-query";
import { View, Text, ScrollView } from "react-native";
import { Container } from "@/components/container";
{{#if (eq api "orpc")}}
import { useQuery } from "@tanstack/react-query";
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { useQuery } from "@tanstack/react-query";
import { trpc } from "@/utils/trpc";
{{/if}}
{{#if (eq backend "convex")}}
import { useQuery } from "convex/react";
import { api } from "@{{ projectName }}/backend/convex/_generated/api.js";
{{/if}}
export default function Home() {
{{#if (eq api "orpc")}}
@@ -15,6 +20,9 @@ export default function Home() {
{{#if (eq api "trpc")}}
const healthCheck = useQuery(trpc.healthCheck.queryOptions());
{{/if}}
{{#if (eq backend "convex")}}
const healthCheck = useQuery(api.healthCheck.get);
{{/if}}
return (
<Container>
@@ -28,15 +36,35 @@ export default function Home() {
<View className="flex-row items-center gap-2">
<View
className={`h-2.5 w-2.5 rounded-full ${
healthCheck.data ? "bg-green-500" : "bg-red-500"
{{#if (or (eq api "orpc") (eq api "trpc"))}}
healthCheck.data ? "bg-green-500" : "bg-red-500"
{{else}}
healthCheck ? "bg-green-500" : "bg-red-500"
{{/if}}
}`}
/>
<Text className="text-sm text-foreground">
{healthCheck.isLoading
? "Checking..."
: healthCheck.data
? "Connected"
: "Disconnected"}
{{#if (eq api "orpc")}}
{healthCheck.isLoading
? "Checking..."
: healthCheck.data
? "Connected"
: "Disconnected"}
{{/if}}
{{#if (eq api "trpc")}}
{healthCheck.isLoading
? "Checking..."
: healthCheck.data
? "Connected"
: "Disconnected"}
{{/if}}
{{#if (eq backend "convex")}}
{healthCheck === undefined
? "Checking..."
: healthCheck === "OK"
? "Connected"
: "Error"}
{{/if}}
</Text>
</View>
</View>

View File

@@ -1,4 +1,8 @@
{{#if (eq backend "convex")}}
import { ConvexProvider, ConvexReactClient } from "convex/react";
{{else}}
import { QueryClientProvider } from "@tanstack/react-query";
{{/if}}
import { Stack } from "expo-router";
import {
DarkTheme,
@@ -35,6 +39,12 @@ export const unstable_settings = {
initialRouteName: "(drawer)",
};
{{#if (eq backend "convex")}}
const convex = new ConvexReactClient(process.env.EXPO_PUBLIC_CONVEX_URL!, {
unsavedChangesWarning: false,
});
{{/if}}
export default function RootLayout() {
const hasMounted = useRef(false);
const { colorScheme, isDarkColorScheme } = useColorScheme();
@@ -58,6 +68,22 @@ export default function RootLayout() {
return null;
}
return (
{{#if (eq backend "convex")}}
<ConvexProvider client={convex}>
<ThemeProvider value={isDarkColorScheme ? DARK_THEME : LIGHT_THEME}>
<StatusBar style={isDarkColorScheme ? "light" : "dark"} />
<GestureHandlerRootView style=\{{ flex: 1 }}>
<Stack>
<Stack.Screen name="(drawer)" options=\{{ headerShown: false }} />
<Stack.Screen
name="modal"
options=\{{ title: "Modal", presentation: "modal" }}
/>
</Stack>
</GestureHandlerRootView>
</ThemeProvider>
</ConvexProvider>
{{else}}
<QueryClientProvider client={queryClient}>
<ThemeProvider value={isDarkColorScheme ? DARK_THEME : LIGHT_THEME}>
<StatusBar style={isDarkColorScheme ? "light" : "dark"} />
@@ -72,6 +98,7 @@ export default function RootLayout() {
</GestureHandlerRootView>
</ThemeProvider>
</QueryClientProvider>
{{/if}}
);
}

View File

@@ -14,7 +14,6 @@
"@radix-ui/react-label": "^2.1.3",
"@radix-ui/react-slot": "^1.2.0",
"@tanstack/react-form": "^1.3.2",
"@tanstack/react-query": "^5.72.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.487.0",
@@ -29,7 +28,6 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@tanstack/react-query-devtools": "^5.72.2",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",

View File

@@ -1,11 +1,16 @@
"use client"
{{#if (eq api "orpc")}}
{{#if (eq backend "convex")}}
import { useQuery } from "convex/react";
import { api } from "@{{projectName}}/backend/convex/_generated/api.js";
{{else}}
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
{{/if}}
{{#if (eq api "trpc")}}
import { trpc } from "@/utils/trpc";
{{/if}}
{{/if}}
import { useQuery } from "@tanstack/react-query";
{{/if}}
const TITLE_TEXT = `
██████╗ ███████╗████████╗████████╗███████╗██████╗
@@ -24,10 +29,11 @@ const TITLE_TEXT = `
`;
export default function Home() {
{{#if (eq api "orpc")}}
{{#if (eq backend "convex")}}
const healthCheck = useQuery(api.healthCheck.get);
{{else if (eq api "orpc")}}
const healthCheck = useQuery(orpc.healthCheck.queryOptions());
{{/if}}
{{#if (eq api "trpc")}}
{{else if (eq api "trpc")}}
const healthCheck = useQuery(trpc.healthCheck.queryOptions());
{{/if}}
@@ -38,6 +44,18 @@ export default function Home() {
<section className="rounded-lg border p-4">
<h2 className="mb-2 font-medium">API Status</h2>
<div className="flex items-center gap-2">
{{#if (eq backend "convex")}}
<div
className={`h-2 w-2 rounded-full ${healthCheck === "OK" ? "bg-green-500" : healthCheck === undefined ? "bg-orange-400" : "bg-red-500"}`}
/>
<span className="text-sm text-muted-foreground">
{healthCheck === undefined
? "Checking..."
: healthCheck === "OK"
? "Connected"
: "Error"}
</span>
{{else}}
<div
className={`h-2 w-2 rounded-full ${healthCheck.data ? "bg-green-500" : "bg-red-500"}`}
/>
@@ -48,46 +66,10 @@ export default function Home() {
? "Connected"
: "Disconnected"}
</span>
{{/if}}
</div>
</section>
<section>
<h2 className="mb-3 font-medium">Core Features</h2>
<ul className="grid grid-cols-2 gap-3">
<FeatureItem
title="Type-Safe API"
description="End-to-end type safety with tRPC"
/>
<FeatureItem
title="Modern React"
description="TanStack Router + TanStack Query"
/>
<FeatureItem
title="Fast Backend"
description="Lightweight Hono server"
/>
<FeatureItem
title="Beautiful UI"
description="TailwindCSS + shadcn/ui components"
/>
</ul>
</section>
</div>
</div>
);
}
function FeatureItem({
title,
description,
}: {
title: string;
description: string;
}) {
return (
<li className="border-l-2 border-primary py-1 pl-3">
<h3 className="font-medium">{title}</h3>
<p className="text-sm text-muted-foreground">{description}</p>
</li>
);
}

View File

@@ -1,14 +1,22 @@
"use client"
{{#if (eq backend "convex")}}
import { ConvexProvider, ConvexReactClient } from "convex/react";
{{else}}
import { QueryClientProvider } from "@tanstack/react-query";
{{#if (eq api "orpc")}}
{{#if (eq api "orpc")}}
import { orpc, ORPCContext, queryClient } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
{{/if}}
{{#if (eq api "trpc")}}
import { queryClient } from "@/utils/trpc";
{{/if}}
{{/if}}
import { ThemeProvider } from "./theme-provider";
import { Toaster } from "./ui/sonner";
{{#if (eq backend "convex")}}
const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!);
{{/if}}
export default function Providers({
children,
}: {
@@ -21,6 +29,9 @@ export default function Providers({
enableSystem
disableTransitionOnChange
>
{{#if (eq backend "convex")}}
<ConvexProvider client={convex}>{children}</ConvexProvider>
{{else}}
<QueryClientProvider client={queryClient}>
{{#if (eq api "orpc")}}
<ORPCContext.Provider value={orpc}>
@@ -31,6 +42,7 @@ export default function Providers({
{children}
{{/if}}
</QueryClientProvider>
{{/if}}
<Toaster richColors />
</ThemeProvider>
)

View File

@@ -17,7 +17,6 @@
"@react-router/node": "^7.4.1",
"@react-router/serve": "^7.4.1",
"@tanstack/react-form": "^1.2.3",
"@tanstack/react-query": "^5.71.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"isbot": "^5.1.17",
@@ -34,7 +33,6 @@
"devDependencies": {
"@react-router/dev": "^7.4.1",
"@tailwindcss/vite": "^4.0.0",
"@tanstack/react-query-devtools": "^5.71.3",
"@types/node": "^20",
"@types/react": "^19.0.1",
"@types/react-dom": "^19.0.1",

View File

@@ -1,5 +1,3 @@
import { QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import {
isRouteErrorResponse,
Links,
@@ -14,11 +12,17 @@ import Header from "./components/header";
import { ThemeProvider } from "./components/theme-provider";
import { Toaster } from "./components/ui/sonner";
{{#if (eq api "orpc")}}
import { orpc, ORPCContext, queryClient } from "./utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { queryClient } from "./utils/trpc";
{{#if (eq backend "convex")}}
import { ConvexProvider, ConvexReactClient } from "convex/react";
{{else}}
import { QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
{{#if (eq api "orpc")}}
import { orpc, ORPCContext, queryClient } from "./utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { queryClient } from "./utils/trpc";
{{/if}}
{{/if}}
export const links: Route.LinksFunction = () => [
@@ -52,7 +56,25 @@ export function Layout({ children }: { children: React.ReactNode }) {
);
}
{{#if (eq api "orpc")}}
{{#if (eq backend "convex")}}
export default function App() {
const convex = new ConvexReactClient(
import.meta.env.VITE_CONVEX_URL as string,
);
return (
<ConvexProvider client={convex}>
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
<div className="grid grid-rows-[auto_1fr] h-svh">
<Header />
<Outlet />
</div>
<Toaster richColors />
</ThemeProvider>
</ConvexProvider>
);
}
{{else if (eq api "orpc")}}
export default function App() {
return (
<QueryClientProvider client={queryClient}>
@@ -69,9 +91,7 @@ export default function App() {
</QueryClientProvider>
);
}
{{/if}}
{{#if (eq api "trpc")}}
{{else if (eq api "trpc")}}
export default function App() {
return (
<QueryClientProvider client={queryClient}>

View File

@@ -1,11 +1,16 @@
import type { Route } from "./+types/_index";
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { trpc } from "@/utils/trpc";
{{/if}}
{{#if (eq backend "convex")}}
import { useQuery } from "convex/react";
import { api } from "@{{projectName}}/backend/convex/_generated/api.js";
{{else}}
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { trpc } from "@/utils/trpc";
{{/if}}
import { useQuery } from "@tanstack/react-query";
{{/if}}
const TITLE_TEXT = `
██████╗ ███████╗████████╗████████╗███████╗██████╗
@@ -28,11 +33,11 @@ export function meta({}: Route.MetaArgs) {
}
export default function Home() {
{{#if (eq api "orpc")}}
{{#if (eq backend "convex")}}
const healthCheck = useQuery(api.healthCheck.get);
{{else if (eq api "orpc")}}
const healthCheck = useQuery(orpc.healthCheck.queryOptions());
{{/if}}
{{#if (eq api "trpc")}}
{{else if (eq api "trpc")}}
const healthCheck = useQuery(trpc.healthCheck.queryOptions());
{{/if}}
@@ -43,6 +48,18 @@ export default function Home() {
<section className="rounded-lg border p-4">
<h2 className="mb-2 font-medium">API Status</h2>
<div className="flex items-center gap-2">
{{#if (eq backend "convex")}}
<div
className={`h-2 w-2 rounded-full ${healthCheck === "OK" ? "bg-green-500" : healthCheck === undefined ? "bg-orange-400" : "bg-red-500"}`}
/>
<span className="text-sm text-muted-foreground">
{healthCheck === undefined
? "Checking..."
: healthCheck === "OK"
? "Connected"
: "Error"}
</span>
{{else}}
<div
className={`h-2 w-2 rounded-full ${
healthCheck.data ? "bg-green-500" : "bg-red-500"
@@ -55,46 +72,10 @@ export default function Home() {
? "Connected"
: "Disconnected"}
</span>
{{/if}}
</div>
</section>
<section>
<h2 className="mb-3 font-medium">Core Features</h2>
<ul className="grid grid-cols-2 gap-3">
<FeatureItem
title="Type-Safe API"
description="End-to-end type safety with tRPC"
/>
<FeatureItem
title="Modern React"
description="TanStack Router + TanStack Query"
/>
<FeatureItem
title="Fast Backend"
description="Lightweight Hono server"
/>
<FeatureItem
title="Beautiful UI"
description="TailwindCSS + shadcn/ui components"
/>
</ul>
</section>
</div>
</div>
);
}
function FeatureItem({
title,
description,
}: {
title: string;
description: string;
}) {
return (
<li className="border-l-2 border-primary py-1 pl-3">
<h3 className="font-medium">{title}</h3>
<p className="text-sm text-muted-foreground">{description}</p>
</li>
);
}

View File

@@ -11,7 +11,6 @@
"check-types": "tsc --noEmit"
},
"devDependencies": {
"@tanstack/react-query-devtools": "^5.69.0",
"@tanstack/react-router-devtools": "^1.114.27",
"@tanstack/router-plugin": "^1.114.27",
"@types/node": "^22.13.13",
@@ -30,7 +29,6 @@
"@radix-ui/react-slot": "^1.1.2",
"@tanstack/react-form": "^1.0.5",
"@tailwindcss/vite": "^4.0.15",
"@tanstack/react-query": "^5.69.0",
"@tanstack/react-router": "^1.114.25",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",

View File

@@ -1,14 +1,20 @@
import { QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createRouter } from "@tanstack/react-router";
import ReactDOM from "react-dom/client";
import Loader from "./components/loader";
import { routeTree } from "./routeTree.gen";
{{#if (eq api "orpc")}}
import { QueryClientProvider } from "@tanstack/react-query";
import { orpc, queryClient } from "./utils/orpc";
{{/if}}
{{#if (eq api "trpc")}}
import { QueryClientProvider } from "@tanstack/react-query";
import { queryClient, trpc } from "./utils/trpc";
{{/if}}
{{#if (eq backend "convex")}}
import { ConvexProvider, ConvexReactClient } from "convex/react";
const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string);
{{/if}}
{{#if (eq api "orpc")}}
const router = createRouter({
@@ -36,8 +42,18 @@ const router = createRouter({
},
});
{{/if}}
{{#if (eq backend "convex")}}
const router = createRouter({
routeTree,
defaultPreload: "intent",
defaultPendingComponent: () => <Loader />,
context: {},
Wrap: function WrapComponent({ children }) {
return <ConvexProvider client={convex}>{children}</ConvexProvider>;
},
});
{{/if}}
// Register things for typesafety
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;

View File

@@ -38,6 +38,9 @@ export interface RouterAppContext {
queryClient: QueryClient;
}
{{/if}}
{{#if (eq backend "convex")}}
export interface RouterAppContext {}
{{/if}}
export const Route = createRootRouteWithContext<RouterAppContext>()({
component: RootComponent,
@@ -106,4 +109,24 @@ function RootComponent() {
</>
);
}
{{/if}}
{{/if}}
{{#if (eq backend "convex")}}
function RootComponent() {
const isFetching = useRouterState({
select: (s) => s.isLoading,
});
return (
<>
<HeadContent />
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
<div className="grid grid-rows-[auto_1fr] h-svh">
<Header />
{isFetching ? <Loader /> : <Outlet />}
</div>
<Toaster richColors />
</ThemeProvider>
<TanStackRouterDevtools position="bottom-left" />
</>
);
}
{{/if}}

View File

@@ -1,11 +1,16 @@
import { createFileRoute } from "@tanstack/react-router";
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
import { useQuery } from "@tanstack/react-query";
{{/if}}
{{#if (eq api "trpc")}}
import { trpc } from "@/utils/trpc";
{{/if}}
import { useQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
{{/if}}
{{#if (eq backend "convex")}}
import { useQuery } from "convex/react";
import { api } from "@{{ projectName }}/backend/convex/_generated/api.js";
{{/if}}
export const Route = createFileRoute("/")({
component: HomeComponent,
@@ -34,6 +39,9 @@ function HomeComponent() {
{{#if (eq api "trpc")}}
const healthCheck = useQuery(trpc.healthCheck.queryOptions());
{{/if}}
{{#if (eq backend "convex")}}
const healthCheck = useQuery(api.healthCheck.get);
{{/if}}
return (
<div className="container mx-auto max-w-3xl px-4 py-2">
@@ -42,6 +50,7 @@ function HomeComponent() {
<section className="rounded-lg border p-4">
<h2 className="mb-2 font-medium">API Status</h2>
<div className="flex items-center gap-2">
{{#if (or (eq api "orpc") (eq api "trpc"))}}
<div
className={`h-2 w-2 rounded-full ${healthCheck.data ? "bg-green-500" : "bg-red-500"}`}
/>
@@ -52,46 +61,22 @@ function HomeComponent() {
? "Connected"
: "Disconnected"}
</span>
{{/if}}
{{#if (eq backend "convex")}}
<div
className={`h-2 w-2 rounded-full ${healthCheck === "OK" ? "bg-green-500" : healthCheck === undefined ? "bg-orange-400" : "bg-red-500"}`}
/>
<span className="text-sm text-muted-foreground">
{healthCheck === undefined
? "Checking..."
: healthCheck === "OK"
? "Connected"
: "Error"}
</span>
{{/if}}
</div>
</section>
<section>
<h2 className="mb-3 font-medium">Core Features</h2>
<ul className="grid grid-cols-2 gap-3">
<FeatureItem
title="Type-Safe API"
description="End-to-end type safety with tRPC"
/>
<FeatureItem
title="Modern React"
description="TanStack Router + TanStack Query"
/>
<FeatureItem
title="Fast Backend"
description="Lightweight Hono server"
/>
<FeatureItem
title="Beautiful UI"
description="TailwindCSS + shadcn/ui components"
/>
</ul>
</section>
</div>
</div>
);
}
function FeatureItem({
title,
description,
}: {
title: string;
description: string;
}) {
return (
<li className="border-l-2 border-primary py-1 pl-3">
<h3 className="font-medium">{title}</h3>
<p className="text-sm text-muted-foreground">{description}</p>
</li>
);
}

View File

@@ -1,3 +1,13 @@
{{#if (eq backend "convex")}}
import { createRouter as createTanStackRouter } from "@tanstack/react-router";
import { QueryClient } from "@tanstack/react-query";
import { routerWithQueryClient } from "@tanstack/react-router-with-query";
import { ConvexQueryClient } from "@convex-dev/react-query";
import { ConvexProvider } from "convex/react";
import { routeTree } from "./routeTree.gen";
import Loader from "./components/loader";
import "./index.css";
{{else}}
import {
QueryCache,
QueryClient,
@@ -7,18 +17,56 @@ import { createRouter as createTanstackRouter } from "@tanstack/react-router";
import Loader from "./components/loader";
import "./index.css";
import { routeTree } from "./routeTree.gen";
{{#if (eq api "trpc")}}
{{#if (eq api "trpc")}}
import { createTRPCClient, httpBatchLink } from "@trpc/client";
import { createTRPCOptionsProxy } from "@trpc/tanstack-react-query";
import { toast } from "sonner";
import type { AppRouter } from "../../server/src/routers";
import { TRPCProvider } from "./utils/trpc";
{{/if}}
{{#if (eq api "orpc")}}
{{/if}}
{{#if (eq api "orpc")}}
import { orpc, ORPCContext, queryClient } from "./utils/orpc";
{{/if}}
{{/if}}
{{#if (eq api "trpc")}}
{{#if (eq backend "convex")}}
export function createRouter() {
const CONVEX_URL = (import.meta as any).env.VITE_CONVEX_URL!;
if (!CONVEX_URL) {
console.error("missing envar VITE_CONVEX_URL");
}
const convexQueryClient = new ConvexQueryClient(CONVEX_URL);
const queryClient: QueryClient = new QueryClient({
defaultOptions: {
queries: {
queryKeyHashFn: convexQueryClient.hashFn(),
queryFn: convexQueryClient.queryFn(),
},
},
});
convexQueryClient.connect(queryClient);
const router = routerWithQueryClient(
createTanStackRouter({
routeTree,
defaultPreload: "intent",
defaultPendingComponent: () => <Loader />,
defaultNotFoundComponent: () => <div>Not Found</div>,
context: { queryClient },
Wrap: ({ children }) => (
<ConvexProvider client={convexQueryClient.convexClient}>
{children}
</ConvexProvider>
),
}),
queryClient,
);
return router;
}
{{else}}
{{#if (eq api "trpc")}}
export const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error) => {
@@ -38,11 +86,7 @@ export const queryClient = new QueryClient({
const trpcClient = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
{{#if (includes frontend 'next')}}
url: `${process.env.NEXT_PUBLIC_SERVER_URL}/trpc`,
{{else}}
url: `${import.meta.env.VITE_SERVER_URL}/trpc`,
{{/if}}
{{#if auth}}
fetch(url, options) {
return fetch(url, {
@@ -59,8 +103,7 @@ const trpc = createTRPCOptionsProxy({
client: trpcClient,
queryClient: queryClient,
});
{{/if}}
{{/if}}
export const createRouter = () => {
const router = createTanstackRouter({
@@ -69,10 +112,10 @@ export const createRouter = () => {
defaultPreloadStaleTime: 0,
{{#if (eq api "trpc")}}
context: { trpc, queryClient },
{{/if}}
{{#if (eq api "orpc")}}
{{/if}}
{{#if (eq api "orpc")}}
context: { orpc, queryClient },
{{/if}}
{{/if}}
defaultPendingComponent: () => <Loader />,
defaultNotFoundComponent: () => <div>Not Found</div>,
Wrap: ({ children }) => (
@@ -93,6 +136,7 @@ export const createRouter = () => {
return router;
};
{{/if}}
// Register the router instance for type safety
declare module "@tanstack/react-router" {

View File

@@ -11,26 +11,28 @@ import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
import Header from "../components/header";
import appCss from "../index.css?url";
import type { QueryClient } from "@tanstack/react-query";
{{#if (eq api "trpc")}}
import type { TRPCOptionsProxy } from "@trpc/tanstack-react-query";
import type { AppRouter } from "../../../server/src/routers";
{{/if}}
{{#if (eq api "orpc")}}
import type { orpc } from "@/utils/orpc";
{{/if}}
import Loader from "@/components/loader";
{{#if (eq api "trpc")}}
{{#if (eq backend "convex")}}
export interface RouterAppContext {
queryClient: QueryClient;
}
{{else}}
{{#if (eq api "trpc")}}
import type { TRPCOptionsProxy } from "@trpc/tanstack-react-query";
import type { AppRouter } from "../../../server/src/routers";
export interface RouterAppContext {
trpc: TRPCOptionsProxy<AppRouter>;
queryClient: QueryClient;
}
{{/if}}
{{#if (eq api "orpc")}}
{{/if}}
{{#if (eq api "orpc")}}
import type { orpc } from "@/utils/orpc";
export interface RouterAppContext {
orpc: typeof orpc;
queryClient: QueryClient;
}
{{/if}}
{{/if}}
export const Route = createRootRouteWithContext<RouterAppContext>()({

View File

@@ -1,11 +1,17 @@
{{#if (eq api "trpc")}}
import { useTRPC } from "@/utils/trpc";
{{/if}}
{{#if (eq api "orpc")}}
import { useORPC } from "@/utils/orpc";
{{/if}}
import { useQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
{{#if (eq backend "convex")}}
import { convexQuery } from "@convex-dev/react-query";
import { useSuspenseQuery } from "@tanstack/react-query";
import { api } from "@{{projectName}}/backend/convex/_generated/api.js";
{{else}}
{{#if (eq api "trpc")}}
import { useTRPC } from "@/utils/trpc";
{{/if}}
{{#if (eq api "orpc")}}
import { useORPC } from "@/utils/orpc";
{{/if}}
import { useQuery } from "@tanstack/react-query";
{{/if}}
export const Route = createFileRoute("/")({
component: HomeComponent,
@@ -28,13 +34,17 @@ const TITLE_TEXT = `
`;
function HomeComponent() {
{{#if (eq api "trpc")}}
{{#if (eq backend "convex")}}
const healthCheck = useSuspenseQuery(convexQuery(api.healthCheck.get, {}));
{{else}}
{{#if (eq api "trpc")}}
const trpc = useTRPC();
const healthCheck = useQuery(trpc.healthCheck.queryOptions());
{{/if}}
{{#if (eq api "orpc")}}
{{/if}}
{{#if (eq api "orpc")}}
const orpc = useORPC();
const healthCheck = useQuery(orpc.healthCheck.queryOptions());
{{/if}}
{{/if}}
return (
@@ -44,6 +54,18 @@ function HomeComponent() {
<section className="rounded-lg border p-4">
<h2 className="mb-2 font-medium">API Status</h2>
<div className="flex items-center gap-2">
{{#if (eq backend "convex")}}
<div
className={`h-2 w-2 rounded-full ${healthCheck.data === "OK" ? "bg-green-500" : healthCheck.isLoading ? "bg-orange-400" : "bg-red-500"}`}
/>
<span className="text-muted-foreground text-sm">
{healthCheck.isLoading
? "Checking..."
: healthCheck.data === "OK"
? "Connected"
: "Error"}
</span>
{{else}}
<div
className={`h-2 w-2 rounded-full ${healthCheck.data ? "bg-green-500" : "bg-red-500"}`}
/>
@@ -54,46 +76,10 @@ function HomeComponent() {
? "Connected"
: "Disconnected"}
</span>
{{/if}}
</div>
</section>
<section>
<h2 className="mb-3 font-medium">Core Features</h2>
<ul className="grid grid-cols-2 gap-3">
<FeatureItem
title="Type-Safe API"
description="End-to-end type safety with tRPC"
/>
<FeatureItem
title="Modern React"
description="TanStack Router + TanStack Query"
/>
<FeatureItem
title="Fast Backend"
description="Lightweight Hono server"
/>
<FeatureItem
title="Beautiful UI"
description="TailwindCSS + shadcn/ui components"
/>
</ul>
</section>
</div>
</div>
);
}
function FeatureItem({
title,
description,
}: {
title: string;
description: string;
}) {
return (
<li className="border-primary border-l-2 py-1 pl-3">
<h3 className="font-medium">{title}</h3>
<p className="text-muted-foreground text-sm">{description}</p>
</li>
);
}