How to access form data in a post request when using React (TypeScript)?

3.6k views Asked by At

I wanted to create a simple signup page using React in TypeScript. My goal was to create two input fields on a signup page asking for a first and last name, and once the form was submitted, it would redirect the user to a page called "complete" that would display their first and last name. I was able to do this using the get method, as I was able to use url parameters as displayed below.

Signup page:

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

export default function SignUpPage() {
  return (
    <>
      <form autoComplete="off" action="/complete" method="get">
        <label htmlFor="firstNameInputField">First Name: </label>
        <input type="text" id="firstNameInputField" name="firstName"/><br />
        <label htmlFor="lastNameInputField">Last Name: </label>
        <input type="text" id="lastNameInputField" name="lastName"/><br />
      
        <input type="submit" value="Submit"/>
      </form>
    </>
  );
}

Complete page:

import { useSearchParams } from 'next/navigation';

export default function SignUpComplete()
{
    const searchParams = useSearchParams();
    const firstName = searchParams.get("firstName");
    const lastName = searchParams.get("lastName");

    return (
    <>
        <p>Thank you for submitting! Your credentials are:</p>
        <p>First name: {firstName}</p>
        <p>Last name: {lastName}</p>
        <br/>
        <a href="http://localhost:3000/login">Click here to login!</a>
    </>
    )
}

However, instead of using the get method, I want to use the post method, as I've heard that it is more protective of a user's information. As such, how can I use the post method to format my signup page like this:

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

export default function SignUpPage() {
  const firstNameRef = useRef(null) as unknown as React.MutableRefObject<HTMLInputElement>;
  const lastNameRef = useRef(null) as unknown as React.MutableRefObject<HTMLInputElement>;

  function submitCredentials()
  {
    // method to send credentials goes here
  }

  return (
    <>
      <form autoComplete="off" action="/complete" method="post" onSubmit={submitCredentials}>
        <label htmlFor="firstNameInputField">First Name: </label>
        <input type="text" id="firstNameInputField" ref={firstNameRef}/><br />
        <label htmlFor="lastNameInputField">Last Name: </label>
        <input type="text" id="lastNameInputField" ref={lastNameRef}/><br />
      
        <input type="submit" value="Submit"/>
      </form>
    </>
  );
}

Or how can I use the post method to format my complete page like this:

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

export default function SignUpComplete()
{
    let firstName = "";
    let lastName = "";
    
    // method to assign firstName and lastName goes here
    
    return (
    <>
        <p>Thank you for submitting! Your credentials are:</p>
        <p>First name: {firstName}</p>
        <p>Last name: {lastName}</p>
        <br/>
        <a href="http://localhost:3000/login">Click here to login!</a>
    </>
    )
}
1

There are 1 answers

0
WordPress Speed On

In React with TypeScript, you can access form data from a POST request by utilizing the FormData object and the fetch() function. Here's an example of how you can do it:

  1. Start by creating a form component in your React application. This component will contain the form elements and handle the submission:

    import React, { useState } from 'react';
    
    const MyForm: React.FC = () => {
      const [formData, setFormData] = useState({
        name: '',
        email: '',
        message: '',
      });
    
      const handleInputChange = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value } = event.target;
        setFormData((prevFormData) => ({
          ...prevFormData,
          [name]: value,
        }));
      };
    
      const handleSubmit = (event: React.FormEvent) => {
        event.preventDefault();
    
        const postData = new FormData();
        postData.append('name', formData.name);
        postData.append('email', formData.email);
        postData.append('message', formData.message);
    
        fetch('/api/endpoint', {
          method: 'POST',
          body: postData,
        })
          .then((response) => response.json())
          .then((data) => {
            // Handle the response data
          })
          .catch((error) => {
            // Handle any errors
          });
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <label>
            Name:
            <input type="text" name="name" value={formData.name} onChange={handleInputChange} />
          </label>
          <label>
            Email:
            <input type="email" name="email" value={formData.email} onChange={handleInputChange} />
          </label>
          <label>
            Message:
            <textarea name="message" value={formData.message} onChange={handleInputChange} />
          </label>
          <button type="submit">Submit</button>
        </form>
      );
    };
    
    export default MyForm;
    
  2. In the handleSubmit function, create a new instance of FormData and append the form data to it using the append method. The name attribute of each form input corresponds to the key in the FormData object.

  3. Use the fetch() function to make a POST request to your server endpoint with the FormData object as the request body.

  4. On the server-side, you can access the form data using the framework or library you are using (e.g., Express.js, Django, etc.) and process it accordingly.

By following this approach, you can access the form data from a POST request in React with TypeScript and send it to your server for further processing. Remember to adjust the endpoint URL and form field names according to your specific requirements.