Is there a way to automatically clear the comments form upon clicking the submit button in Next.js 14?

I need some assistance with clearing the previous inputted comment in my comment form after the submit button is clicked. I want to make it easier for users by automatically clearing the input field for a new comment. Here is the code I have so far, any help would be highly appreciated! I'm uncertain whether I should separate the page and move the comments form to a separate components folder, along with the Vercel database request.

import { notFound } from "next/navigation";
import Image from "next/image";
import { revalidatePath } from "next/cache";
import Link from "next/link";
import { HiPencilAlt } from "react-icons/hi";
import RemoveBtn from "@/app/components/RemoveBtn";
import RemoveBtnComments from "@/app/components/RemoveBtnComments";
export default async function Page({ params }) {
 //get single post
 console.log(params.singlePost);
 const post = (
   await sql`SELECT * FROM posts01 WHERE post_id = ${params.singlePost} `
 ).rows[0];
 const comments = (
   await sql`SELECT * FROM comments01 WHERE post_id = ${params.singlePost}`
 ).rows;
 //handle posts
 async function handleComments(formData) {
   "use server";
   const comment = formData.get("comment");
   const username = formData.get("username");
   await sql`INSERT INTO comments01 (username, comment, post_id)
        VALUES (${username}, ${comment}, ${post.post_id}) `;
   console.log("comment saved");

   revalidatePath(`/allPosts/${params.singlePost}`);
 }
 if (!post) {
   notFound();
 }
 return (
   //display posts
   <>
     {/* //div that contains all */}
     <div>
       {/* //div that contains post */}
       <div>
         <h2 className="text-2xl font-bold mb-4">{post.title}</h2>
         <div className="flex justify-end gap-5">
           {/* delete post */}
           <RemoveBtn post_id={post.post_id} />
           {/* //edit button */}
           <Link href={`${params.singlePost}/editPost`}>
             <HiPencilAlt size={24} />
           </Link>
         </div>
         <h3 className="text-lg mb-4">{post.content}</h3>
         {/* display image_url */}
         {post.image_url ? (
           <Image
             src={post.image_url}
             alt={`image of ${post.title}`}
             width={300}
             height={300}
           />
         ) : (
           <h3>Image unavailable</h3>
         )}
       </div>
       {/* //comments */}
       <div>
         <h4 className="text-xl font-bold mb-4">Comments</h4>
         <div className="mb-4">
           <form action={handleComments} className="text-black flex">
             <input
               name="username"
               placeholder="Username"
               value={comments.username}
               className="mr-2 px-4 py-2 border border-gray-300 rounded-md"
             />
             <input
               name="comment"
               placeholder="Comment..."
               value={comments.comment}
               className="flex-1 mr-2 px-4 py-2 border border-gray-300 rounded-md"
             />
             <button
               type="submit"
               className="px-4 py-2 bg-blue-500 text-white font-bold rounded-md hover:bg-blue-600"
             >
               Submit
             </button>
           </form>
         </div>
         <div>
           {comments.map((comment) => (
             <div
               className="bg-gray-100 rounded-md p-4 mb-4"
               key={comment.comment_id}
             >
               <p className="font-bold text-lg mb-2">{comment.username}</p>
               <div>
                 <p>{comment.comment}</p>
               </div>
               {/* delete comment */}
               <div className="flex justify-end gap-5">
                 <RemoveBtnComments comment_id={comment.comment_id} />
               </div>
             </div>
           ))}
         </div>
       </div>
     </div>
   </>
 );
}

Answer №1

Summary:

To improve code organization, store comment data in state and clear it upon submission.

Component Architecture:

Separate component responsible for API requests from rendering logic using the Container-Component Pattern.

Currently, the Page component handles API requests, rendering, and user interactions.

Review the code snippet below for an example:

import React, { useEffect, useState } from 'react';

function PageContainer({ params }) {
  // State for post and comment data
  const [postData, setPostData] = useState({});
  const [commentData, setCommentData] = useState([]);

  // Fetch data using useEffect
  useEffect(() => {
    const fetchData = async() => {
      const post = (
        await sql`SELECT * FROM posts01 WHERE post_id = ${params.singlePost} `
      ).rows[0];
      const comments = (
        await sql`SELECT * FROM comments01 WHERE post_id = ${params.singlePost}`
      ).rows;

      setPostData(post);
      setCommentData(comments);
    }

    fetchData();
  }, []);

  // Return Page component with data and submitComment function
}

function Page({ title, post_id, content, image_url, singlePost, comments, userName, submitComment }) {
  // State for user input
  const [comment, setComment] = useState('');

  const handleCommentSubmit = async (e) => {
    // Handle form submission
  }

  // Render content, comments, and form
}

The PageContainer fetches post and comment data and passes it to the Page component along with a submit function. The Page component displays content and comments, managing user input and clearing it upon submission.

Consider breaking the design into smaller components like Image, CommentForm, and CommentList for better organization.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Saving data to a database using jQuery Ajax when multiple checkboxes are checked

Looking for a solution to store checkbox values into a database using jQuery Ajax to PHP. https://i.sstatic.net/tdjm9.png To see a live demo, click here. The image above illustrates that upon checking certain checkboxes and clicking Update, the checkbox ...

Sign up with React: A seamless registration form for

Currently, I am working on integrating a signup feature into my React application Here is a snippet of the code from my signup.JSX file: const Senddata = () => { // if(isvalid.username && // isvalid.password && ...

What is the process for executing Express's scaffold by utilizing "nodemon" and the basic "node" command instead of relying on the "npm start" command?

Could you help me locate where I need to make changes in my package.json file? Here is the content of my package.json: { "name": "xyz", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www" }, "dependencies": { ...

How can I reference MyClass.new as a method in Typescript?

Within my code, I have an array of objects and each object is structured like this: { id: 'string', name: 'string' } There's a class defined as follows: class User { constructor(obj: Record<string, string>) { Object.as ...

Populating a ListBox without the need to constantly scroll upwards

I'm currently facing an issue with a ListBox that displays online users fetched from a MySQL database. Every second, the ListBox is updated with new users. The problem arises when adding an item to the ListBox causes it to scroll up, which I want to a ...

Trouble transferring $rootScope.currentUser between AngularJS profile and settings page

I am in the process of setting up a site using Angular, Express, Node, and Passport. Currently, I am configuring Angular to monitor the $rootScope.currentUser variable with the following code: app.run(function ($rootScope, $location, Auth) { // Watch ...

The Rails text area fails to load through JavaScript when a line break is detected

My comment form has a feature that displays the content of the text area using js. It functions properly unless a new line is entered in the text area, in which case it does not show up right away. However, after refreshing the page, the comment appears wi ...

React Select only enabling single selection at a time

Currently, I am in the process of updating my react app to version 16.8 and also updating all associated libraries. One issue that has come up is with two drop-down selects from Material UI. Since the update, the multi-select option no longer allows multip ...

Initiate the process of displaying data on a datetime chart using Highcharts

I am currently developing a yearly chart, but I've encountered a small issue. The chart begins in January, however there is no data available until May. The client specifically wants the chart to only display when there is data available, and unfortu ...

Is there a method to determine if localForage/indexedDb is currently handling data operations?

Currently, I am working on a webapp that utilizes async localForage (specifically angular localForage). My goal is to alert users if they attempt to close the browser window while there are ongoing localForage operations. I have observed that some browser ...

Is there a way to prevent the imported JQuery from causing issues with current code implementations?

Being a novice developer in Html/Javascript/CSS/Jquery coding, I recently encountered an issue while integrating Jquery into my project. When I imported Jquery, the styling of simple buttons went haywire. Jquery worked perfectly fine when using its classes ...

A guide on generating indices for icosahedronbuffergeometry using three.js

I am facing an issue and struggling to find a solution. I am looking for an alternative method to texture a sphere in three.js by using icosahedronbuffergeometry instead of spherebuffergeometry with additional code to generate indices for rendering using d ...

When attempting to access endpoints from other computers, the connection to Express.js is being refused

I have set up an Express server and React for the frontend. The express server is running on port 5000 and React on port 3000. Additionally, I am using JWT tokens for authentication. When I login to the app from the computer it is running on, everything w ...

A method to verify the presence of a specific element within a list using JavaScript

I'm trying to validate if the list retrieved from the application contains the expected element. Can you please review my code and let me know where I might be making a mistake? this.verifyOptionsInDropdown = async function(){ var optionList = a ...

Having trouble getting the ReactJS AXIOS post function to work properly?

Error in console: [1]: https://i.sstatic.net/xOfUV.png issue with axios request .post("https://bootcamp-2022.devtest.ge/api/application", { token: "7e475dfc-0daa-4108-81c8-d6c62a3df4ca", first_name: JSON.parse(localStorage.ge ...

"Encountered a problem with Next JS API while trying to fetch data from the app directory

import { NextResponse } from "next/server"; export async function POST(request: Request) { const data = await request.json(); console.log(data); return NextResponse.json({ foo: "boo" }); } next version = "next": &quo ...

Property referencing for change detection is a valuable technique

I'm struggling to update my template when changing a boolean property that is referenced in another array property. I expected the changes to reflect in my template, but they are not showing up. Upon initial load, everything appears in its initial st ...

Experimenting with a customizable Vue.js autocomplete feature

Check out this sample code: https://jsfiddle.net/JLLMNCHR/09qtwbL6/96/ The following is the HTML code: <div id="app"> <button type="button" v-on:click="displayVal()">Button1</button> <autocomplete v- ...

The challenge of default Vuetify styles within a Nuxt environment

Here is my code snippet: <div class="cd-page__details-wrapper"> <v-text-field label="Outlined" placeholder="Outlined" outlined ></v-text-field> </div> Unfortunately, something unexpecte ...

Placing a div with position:absolute inside another div with position:absolute and turning them into position:fixed

HTML <div class="box1"></div> <div class="box2"> <div class="box3"></div> </div> CSS Properties of box1, box2 and box3 are: box1 { position: absolute; z-index: 100; background-color: rgba(39, 39, 39, 0.3) ...