Deleting Data with Xata

So currently, our to-do app can Read data from Xata, and Update to-do items. But what good is keeping a list of already done to-dos? Let's offer our users a way to remove them, adding the Delete to CRUD (Create, Read, Update, and Delete). Let's explore how we can further CRUD-ify our Xata app in this guide.

If you're joining us in the middle, we covered updating data with Xata in the previous section. Maybe read that first before coming here for more context.

Creating a Delete Button

Currently, our to-do app has no button to delete a to-do item. Let's add a button to delete a to-do item.

// ./pages/index.tsx

import { FC } from "react";
import { xata } from "../util/xataClient";

type Props = Awaited<ReturnType<typeof getServerSideProps>>["props"];

const Index: FC<Props> = ({ todos }) => {
  return (
    <main>
      <h1>My To-do List</h1>
      <ul>
        <li>
          {todos.map((t) => (
+            <>
              <label key={t.id}>
                <input
                  onClick={() => {
                    fetch("/api/toggle-todo", {
                      method: "POST",
                      headers: {
                        "Content-Type": "application/json",
                      },
                      body: JSON.stringify({ id: t.id, is_done: !t.is_done }),
                    }).then(() => {
                      window.location.reload();
                    });
                  }}
                  type="checkbox"
                  checked={t.is_done}
                />
                {t.label}
              </label>
+              <button
+                onClick={() => {
+                  fetch("/api/delete-todo", {
+                    method: "POST",
+                    headers: {
+                      "Content-Type": "application/json",
+                    },
+                    body: JSON.stringify({ id: t.id }),
+                  }).then(() => {
+                    window.location.reload();
+                  });
+                }}
+              >
+                Delete
+              </button>
+            </>
          ))}
        </li>
      </ul>
    </main>
  );
};

export const getServerSideProps = async () => {
  const todos = await xata.db.items.getMany();
  return { props: { todos } };
};

export default Index;

Just like we did previously, we've added a fetch call to a Next.js API route, but this time to delete a to-do item. Of course, the API route doesn't exist. So let's create a new one, in ./pages/api/delete-todo.ts.

// ./pages/api/delete-todo.ts
import { NextApiHandler } from "next";
import { xata } from "../../util/xataClient";

const handler: NextApiHandler = async (req, res) => {
  const { id } = req.body;
  await xata.db.items.delete(id);
  res.end();
};

export default handler;

All we're doing here is calling .delete and giving it an id, which we have from the user interface. Xata handles the rest. When we run this, we can now delete to-do items. Yay!

Conclusion?

Wait! We've deleted all of our to-do items now. :( How can we create more? Let's wrap this up by allowing our users to create to-do items using Xata.


Last modified 1 mo17 days ago