How To Insert and send Form Data In Api In Nextjs

How-To-Insert-and-send-Form-Data-In-Api-In-Nextjs
573 Views
0
(0)

Welcome to another insightful tutorial brought to you by CodexCoach, your trusted companion in the coding journey. Today, we’re diving deep into the world of React JS and Next.js to demonstrate how you can efficiently send form data to an API.

Whether you’re building a contact form, a survey, or any application that collects user input, mastering this skill is crucial. Let’s embark on this learning adventure together, ensuring you’re equipped with the knowledge to seamlessly integrate form data with APIs.

Introduction

React JS has revolutionized the way we build web applications, offering a seamless experience for both developers and users. When paired with Next.js, React’s capabilities are significantly enhanced, allowing for server-side rendering and static site generation, among other benefits.

A common requirement in web development is sending form data to a backend API. This process involves capturing user input, validating the data, and making an HTTP request to send the data to the server. Today, we’ll cover how to accomplish this using React JS and Next.js.

Install Library in Project

Before we start, ensure that your project environment is set up correctly. We’ll be using Axios, a popular HTTP client for making requests, for its simplicity and ease of use. If Axios is not already installed in your project, let’s add it:

- npm install axios

Check the Axios if not then apply the command in project terminal

If you’re unsure whether Axios is installed, you can verify by checking your package.json file or by running the installation command. It won’t harm if Axios is already installed; npm will simply skip the installation.

Multi Select Checkbox

Handling multiple selections, such as checkboxes, is a common requirement. React makes this process straightforward by allowing you to manage the state of each checkbox. Here’s a quick snippet on how to handle multiple checkboxes:

const handleInterestChange = (event) => {
   const selectedInterest = event.target.value;


   // Check if the interest is already selected
   const isInterestSelected = selectedInterests.includes(selectedInterest);


   // If selected, remove from the array; otherwise, add it
   const updatedInterests = isInterestSelected
     ? selectedInterests.filter((interest) => interest !== selectedInterest)
     : [...selectedInterests, selectedInterest];


   setSelectedInterests(updatedInterests);
 };

Take Input Value

Capturing input values in React is done through the useState hook. For each input field, you’ll create a state that updates on every change event:

const formElement = document.querySelector("#details_form");
   const formData = new FormData(formElement);

Take Data Name from Input

To effectively send form data to an API, you need to collect the name attribute from your input fields. This ensures that your data object keys match your backend expectations. Here’s how you might capture both value and name:

let name = formData.get("name");

Set Error If Data Was Not Inserted in Input

Input validation is crucial. If a user fails to fill out a required field, you should inform them of the mistake. Here’s a simple way to set an error state:

if (!name || name.trim() === "") {
     error.name = "First Name is required*";
   }

Inserting Data In API

Now, for the main event: sending the form data to an API. Using Axios, we’ll make a POST request. Ensure to validate your data before attempting to send it:

let data = JSON.stringify({
       name: name
     });
let config = {
   method: "post",
   url: ["You can add your api Hear "],
   headers: {
     "Content-Type": "application/json",
   },
   data: data,
  };
axios
 .request(config)
 .then((response) => { console.log(JSON.stringify(response.data));
       })
       .catch((error) => {
         console.log(error);
       });

Download Demo from Here

To solidify your understanding and give you hands-on experience, CodexCoach has prepared a downloadable demo.

This demo includes everything we’ve covered, allowing you to explore the code, make modifications, and see the results in real-time. Download the demo from here.

How useful was this blog?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this blog.

By Dhruv Lakkad

Hello, my name is Dhruv. I am located in Gujarat. I have 1.5+ years of experience in Node.js & Next.js web development areas. Currently, I am working on the CodexCoach site. So keep reading Node.js & Next.js related blogs and enhance your NodeJS & NextJS web development skills by reading my guides. Thank you!

Leave a comment

Your email address will not be published. Required fields are marked *