Created
May 17, 2024 17:39
-
-
Save kmelve/27ef655c86ec3b36090e0f0aeeaea396 to your computer and use it in GitHub Desktop.
Minimal totally-not-ready-for-prod Todo list example using Sanity Live Content API and Next.js Server Actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { redirect } from "next/navigation" | |
import { createClient } from "next-sanity" | |
const client = createClient({ | |
apiVersion: "vX", | |
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET, | |
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, | |
token: process.env.SANITY_WRITE_TOKEN, | |
useCdn: true, | |
}) | |
import { defineSanityFetch } from "next-sanity/live-subscription" | |
const sanityFetch = defineSanityFetch({ | |
client, | |
searchParamKey: "lastLiveEventId", | |
}) | |
export default async function ToDo({ searchParams: { lastLiveEventId } }: any) { | |
const [tasks, LiveSubscription]: [any, any] = await sanityFetch({ | |
query: `*[_type == "task"]`, | |
lastLiveEventId, | |
}) | |
async function createTask(formData: FormData) { | |
"use server" | |
const task = formData.get("task") | |
if (task) { | |
await client.create({ | |
_type: "task", | |
task, | |
}) | |
redirect("/todo") | |
} | |
} | |
async function deleteTask(formData: FormData) { | |
"use server" | |
const taskId = formData.get("taskId")?.toString() | |
if (taskId) { | |
await client.delete(taskId) | |
} | |
redirect("/todo") | |
} | |
return ( | |
<div> | |
<form action={createTask}> | |
<input type="text" name="task" /> | |
<button type="submit">Add</button> | |
</form> | |
<ul> | |
{tasks.map((task: any) => ( | |
<li key={task._id}> | |
<form action={deleteTask}> | |
<input type="hidden" name="taskId" value={task._id} /> | |
<span>{task.task}</span> | |
<button type="submit"> | |
Done | |
</button> | |
</form> | |
</li> | |
))} | |
</ul> | |
<LiveSubscription /> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment