Fundamentals
Server Actions

Server Actions: Streamlining Data Operations in AgriMarket

Server Actions are a game-changer in Next.js 13, allowing you to execute server-side code directly within your components. This eliminates the need for separate API routes, simplifying data fetching and manipulation within your application.

How Server Actions Work in AgriMarket:

Imagine you want to create a new product entry in the marketplace. Here's how Server Actions can make it happen:

  1. Define the Server Action:

    // app/actions.js (or a dedicated actions folder)
     
    'use server';
     
    import prisma from '@/lib/prisma'; // Import your Prisma client
     
    export const createProduct = async (productData) => {
      try {
        const newProduct = await prisma.product.create({
          data: productData, // Pass the product data from your component
        });
        return newProduct; // Return the created product
      } catch (error) {
        console.error('Error creating product:', error);
        throw new Error('Failed to create product'); // Handle errors gracefully
      }
    };
  2. Use the Server Action in Your Component:

    // pages/products/create.js
     
    import { createProduct } from '@/lib/createProduct'; // Import the action
     
    function CreateProductForm() {
      const res = createProduct() // Import the action
     
      // ... form fields and other UI elements
     
      const handleSubmit = async (event) => {
        event.preventDefault();
        const productData = { ... }; // Collect form data
     
        try {
          const newProduct = await createProduct(productData);
          // Handle success: display confirmation, redirect, etc.
        } catch (error) {
          // Handle errors: display error messages to the user
        }
      };
     
      return (
        <form onSubmit={handleSubmit}>
          {/* ... form elements and submit button */}
        </form>
      );
    }
     
    export default CreateProductForm;

Benefits of Server Actions:

  • Simplified Data Operations: Server Actions provide a clean way to interact with your database from components.
  • Enhanced Security: Sensitive data processing occurs securely on the server.
  • Improved Performance: Optimized data fetching can lead to faster page loads.

By leveraging Server Actions in AgriMarket, you can build a robust and efficient platform for farmers and consumers.