NextJS crud example

Here is a simple Next.js CRUD example:

pages/index.js

JavaScript
import React, { useState } from "react";

const Index = () => {
  const [users, setUsers] = useState([]);

  const fetchUsers = async () => {
    const response = await fetch("/api/users");
    const data = await response.json();
    setUsers(data);
  };

  const handleCreateUser = async (user) => {
    const response = await fetch("/api/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(user),
    });
    const data = await response.json();
    setUsers([...users, data]);
  };

  const handleUpdateUser = async (user) => {
    const response = await fetch(`/api/users/${user.id}`, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(user),
    });
    const data = await response.json();
    setUsers(users.map((user) => (user.id === data.id ? data : user)));
  };

  const handleDeleteUser = async (id) => {
    const response = await fetch(`/api/users/${id}`, {
      method: "DELETE",
    });
    await response.json();
    setUsers(users.filter((user) => user.id !== id));
  };

  React.useEffect(() => {
    fetchUsers();
  }, []);

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {users.map((user) => (
          <li key={user.id}>
            {user.name} ({user.email})
            <button onClick={() => handleUpdateUser(user)}>Update</button>
            <button onClick={() => handleDeleteUser(user.id)}>Delete</button>
          </li>
        ))}
      </ul>

      <form onSubmit={(e) => handleCreateUser(e.target)}>
        <input type="text" name="name" placeholder="Name" />
        <input type="email" name="email" placeholder="Email" />
        <button type="submit">Create</button>
      </form>
    </div>
  );
};

export default Index;

api/users.js

JavaScript
import { NextApiRequest, NextApiResponse } from "next";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  switch (req.method) {
    case "GET":
      const users = await prisma.user.findMany();
      res.json(users);
      break;
    case "POST":
      const user = await prisma.user.create({
        data: req.body,
      });
      res.json(user);
      break;
    case "PUT":
      const updatedUser = await prisma.user.update({
        where: {
          id: req.body.id,
        },
        data: req.body,
      });
      res.json(updatedUser);
      break;
    case "DELETE":
      const deletedUser = await prisma.user.delete({
        where: {
          id: req.query.id,
        },
      });
      res.json(deletedUser);
      break;
    default:
      res.status(405).json({ message: "Method not allowed" });
  }
}

To run this example, install Next.js and create a new Next.js project. Then, copy the above code into the pages/ and api/ directories of your project.

Once you have copied the code, start the Next.js development server:

npm run dev

You can then open your web browser and navigate to http://localhost:3000 to view your example application.

This is just a simple example, but it should give you a good starting point for building CRUD applications with Next.js. 

No comments:

Post a Comment