building-a-crud-application-with-react-nextjs-and-prisma.html

Building a CRUD Application with React, Next.js, and Prisma

In today's fast-paced development environment, mastering modern web technologies is essential. One of the most effective ways to build dynamic web applications is by using React, Next.js, and Prisma. This article will guide you through the process of building a CRUD (Create, Read, Update, Delete) application using these powerful tools.

What is a CRUD Application?

A CRUD application is a type of software that allows users to create, read, update, and delete data. It's a fundamental concept in web development, especially when dealing with databases. Common use cases include:

  • Blog Platforms: Users can create posts, read existing ones, edit content, and delete posts.
  • Inventory Systems: Manage product listings by adding new products, viewing details, updating stock, and removing items.
  • User Management Tools: Create user profiles, view details, modify information, and delete accounts.

Why Use React, Next.js, and Prisma?

  • React: A popular JavaScript library for building user interfaces, React allows developers to create reusable UI components, resulting in fast and interactive web applications.

  • Next.js: A React framework that offers server-side rendering, static site generation, and API routes, making it easier to build fully functioning applications with SEO benefits.

  • Prisma: An ORM (Object-Relational Mapping) tool that simplifies database interactions. It provides a type-safe database client that allows for seamless querying of databases.

Setting Up Your Environment

Before diving into coding, let’s set up our development environment. Ensure you have Node.js and npm installed. You can check this by running:

node -v
npm -v

If you don’t have them installed, download and install Node.js from Node.js official website.

Step 1: Create a Next.js Application

Start by creating a new Next.js application. Open your terminal and run:

npx create-next-app my-crud-app
cd my-crud-app

Step 2: Install Prisma and Database Driver

Next, install Prisma and a database driver. For this example, we will use SQLite for simplicity:

npm install prisma --save-dev
npm install @prisma/client

Step 3: Initialize Prisma

Run the following command to initialize Prisma and create a prisma directory:

npx prisma init

This command generates a .env file for your database connection string and a schema.prisma file.

Step 4: Configure Your Database

Edit the schema.prisma file to define your data models. For example, let’s create a simple Post model:

datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}

generator client {
  provider = "prisma-client-js"
}

model Post {
  id      Int     @id @default(autoincrement())
  title   String
  content String
}

Step 5: Migrate Your Database

Run the migration command to create your database schema:

npx prisma migrate dev --name init

This command will create a new SQLite database file (dev.db) and apply the schema defined in schema.prisma.

Building the CRUD Functionality

Step 6: Create API Routes

Next, we will create API routes for our CRUD operations. Inside the pages/api folder, create a new folder named posts and create a file called index.js:

// pages/api/posts/index.js
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function handler(req, res) {
  if (req.method === 'GET') {
    const posts = await prisma.post.findMany();
    res.json(posts);
  } else if (req.method === 'POST') {
    const { title, content } = req.body;
    const post = await prisma.post.create({
      data: { title, content },
    });
    res.status(201).json(post);
  }
}

Step 7: Create a Post Component

Now, let’s create a simple React component to display and add posts. Create a new file PostForm.js in the components directory:

// components/PostForm.js
import { useState } from 'react';

const PostForm = () => {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    const res = await fetch('/api/posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ title, content }),
    });

    if (res.ok) {
      const newPost = await res.json();
      console.log('Post created:', newPost);
      setTitle('');
      setContent('');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        placeholder="Title"
        required
      />
      <textarea
        value={content}
        onChange={(e) => setContent(e.target.value)}
        placeholder="Content"
        required
      />
      <button type="submit">Create Post</button>
    </form>
  );
};

export default PostForm;

Step 8: Display Posts

Now, let’s fetch and display the posts in our main page. Edit pages/index.js:

// pages/index.js
import { useEffect, useState } from 'react';
import PostForm from '../components/PostForm';

const Home = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const fetchPosts = async () => {
      const res = await fetch('/api/posts');
      const data = await res.json();
      setPosts(data);
    };

    fetchPosts();
  }, []);

  return (
    <div>
      <h1>My CRUD Application</h1>
      <PostForm />
      <h2>Posts</h2>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.content}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Home;

Step 9: Testing Your Application

Run your application using:

npm run dev

Navigate to http://localhost:3000 to see your CRUD application in action. You should be able to create new posts and see them displayed on the page.

Conclusion

Building a CRUD application with React, Next.js, and Prisma is an excellent way to get hands-on experience with modern web technologies. You’ve learned how to set up your environment, create a database schema, implement API routes, and build a user interface for interacting with your data.

As you continue to explore and expand your application, consider adding features like user authentication, error handling, and data validation for a more robust experience. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.