I am not able to link the contact form input written in next.js with postgres in vercel

21 Views Asked by At

I have created a contact form in next.js. I want that as soon as user put the input and press the send button. The data should get input into the database. I am using database provided by postGres vercel.

I have created on contact form. These are the code for the contact form. `

"use client"
import './page_module.css';
import { useState } from "react";

export default function ContactForm() {
  const [fullname, setFullname] = useState("");
  const [email, setEmail] = useState("");
  const [mobile, setMobile] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState([]);
  const [success, setSuccess] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();

    const formData = {
      fullname,
      email,
      mobile,
      message
    };

    try {
      const res = await fetch("/api/add-contact", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });
      
      const data = await res.json();
      if (data.success) {
        setSuccess(true);
        setError([]);
        setFullname("");
        setEmail("");
        setMobile("");
        setMessage("");
      } else {
        setError([data.msg]);
        setSuccess(false);
      }
    } catch (error) {
      console.error("Error submitting form:", error);
      setError(["An error occurred. Please try again later."]);
      setSuccess(false);
    }
  };

  return (
    <div className="contact-form-container">
      <h1>Contact Us</h1>
      <p>Please fill in the details:</p>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="fullname">Full Name</label>
          <input
            onChange={(e) => setFullname(e.target.value)}
            value={fullname}
            type="text"
            id="fullname"
            placeholder="Harsh Ranjan"
          />
        </div>

        <div>
          <label htmlFor="email">Email</label>
          <input
            onChange={(e) => setEmail(e.target.value)}
            value={email}
            type="text"
            id="email"
            placeholder="[email protected]"
          />
        </div>

        <div>
          <label htmlFor="mobile">Mobile No</label>
          <input
            onChange={(e) => setMobile(e.target.value)}
            value={mobile}
            type="text"
            id="mobile"
            placeholder="Enter your mobile number"
          />
        </div>

        <div>
          <label htmlFor="message">Your Message</label>
          <textarea
            onChange={(e) => setMessage(e.target.value)}
            value={message}
            id="message"
            placeholder="Type your message here..."
          ></textarea>
        </div>
        <button type="submit">Send</button>
      </form>

      {/* Error messages */}
      {error.length > 0 && (
        <div className="error-message">
          {error.map((errorMsg, index) => (
            <div key={index}>{errorMsg}</div>
          ))}
        </div>
      )}

      {/* Success message */}
      {success && (
        <div className="success-message">Form submitted successfully!</div>
      )}
    </div>
  );
}

This contact form I am linking with api. Inside the api,I have created folder named add-contact. Inside add-contact folder, i have created one sub folder named route.js. I am linking the code for the same.

import { sql } from '@vercel/postgres';
import { createClient } from '@vercel/postgres';

const db = createClient({
  connectionString: process.env.DATABASE_URL,
  ssl: {
    rejectUnauthorized: false,
  },
});

export async function POST(req, res) {
  if (req.method === 'POST') {
    const { fullname, email, mobile, message } = req.body;

    try {
      await db.connect();

      await db.query(
        sql`INSERT INTO user_Info (fullname, email, mobile, message) VALUES (${fullname}, ${email}, ${mobile}, ${message})`
      );

      await db.end();

      res.status(201).json({ success: true, message: 'Form data submitted successfully' });
    } catch (error) {
      console.error('Error inserting data:', error);
      await db.end();
      res.status(500).json({ success: false, error: 'Internal server error' });
    }
  } else {
    res.status(405).json({ error: 'Method Not Allowed' });
  }
}
0

There are 0 best solutions below