I'm seeing a message in the console that says "Form submission canceled because the form is not connected." Any idea why this is happening?

For the life of me, I can't figure out why this code refuses to run the handleSubmit function. Essentially, the form is supposed to take an input and execute the handleSubmit function upon submission. This function then makes a POST request to an API route with the email and userId. However, instead of logging these values to the console, I keep receiving a warning that says

Form submission canceled because the form is not connected
. Can anyone point out what I might be missing or doing wrong? Here is the code snippet:

import { Fragment, useState } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import Image from 'next/image';

export default function Team({ show, setShow, userId }) {
    const [email, setEmail] = useState({ userId: userId, email: "" });
    const [emailMessage, setEmailMessage] = useState("...");
    const [emailSent, setEmailSent] = useState(false);

    const handleChange = (e) => {
        e.preventDefault();
        const { name, value } = e.target;
        setEmail({ ...email, [name]: value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await fetch("/api/team-members", {
                method: "POST",
                 headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ userId: email.userId, email: email.email })
            });

            const data = await response.json();
            console.log(email.userId, email.email) //This is not logging to the console
            console.log("DATA", data); //This is not logging to the console
        } catch (error) {
            console.error("Error fetching data:", error);
            setEmailMessage("An error occurred while sending the invite.");
        }
    };

    return (
        <>
            <div >
                {emailSent ? (
                    <>
                        <button
                            type="button"
                            onClick={() => setShow(false)}
                        >
                            Close
                        </button>
                    </>
                ) : (
                    <form onSubmit={handleSubmit}>
                        <label htmlFor="email">
                            Member's email
                        </label>
                        <p>Please enter one or more emails separated by commas ','</p>
                        <input
                            id="email"
                            name="email"
                            type="email"
                            onChange={handleChange}
                            autoComplete="email"
                            value={email.email}
                            required
                            placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="20454d41494c604558414d504c450e434f4d">[email protected]</a>"
                        />
                        <button type="submit" onClick={() => setEmailSent(true)}>
                            Submit
                        </button>
                    </form>
                )}
            </div>
        </>
    )
}

Answer №1

Upon clicking the button, the action of sending an email is triggered and the form is swiftly removed from the DOM.

This process occurs prior to the execution of the form's submit event handler.

As a result, the browser attempts to submit the form, only to find that it has already been removed from the DOM.

To avoid this issue, it is advisable to consolidate all actions within a single submit event handler. Delay setting the email sent status until after invoking preventDefault.

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

Mean stack authentication issue: missing token

Overview: Currently, I'm in the process of developing an application that utilizes node/express for the backend, mongo as the database, and angular for the frontend. User authentication is handled through jsonwebtoken, where a token is stored in local ...

How can I pass a PHP variable to a JavaScript variable using PHP and JQuery/JavaScript?

I am facing a challenge with a large <select> input that is used across multiple pages. My idea is to separate this dropdown box into its own PHP file and load it externally using JQuery. Is this approach feasible? Here's an outline of what I ha ...

"Converting a basic function into a promise for an AngularJS tutorial: How to handle the error message '

To help my colleagues understand AngularJS, I am creating a dummy exercise. In this example, I want to call a service that provides an Object Array to be passed into a Controller and assigned to a $scope variable (using information about the Beatles). Inst ...

Creating a pair of linked dropdown menus in ReactJS that open simultaneously

Having two dropdown menus can be a bit cumbersome, especially when you have functions dedicated to opening each one individually. It would be more efficient to combine them into one function for simplicity. If anyone has a solution for this, I would greatl ...

What's better in React: using pure components or non-pure components? Is it okay to fetch data in componentDidMount or

Exploring React in Meteor has led me to observe two distinct approaches... Take the meteor leaderboard example, where a list of players displays their names and scores. The pure approach involves fetching all players and passing them into the playersList ...

Extract hidden form variables using a function in PHP

Here is the JavaScript function that I have written: function GetCellValues() { var rows = document.getElementsByTagName('tr'); var str = ''; for (var c = 1 ; c < rows.length ; c++) { str += '\n&apo ...

No results appearing in the output section

While developing a website using React, I encountered an error that said useState is defined but never used in the navbar component. To address this, I made changes to my ESLint configuration in the package.json file: "rules": { "eqeqe ...

Encountering an issue when attempting to host a Next.js application on Vercel

Why is it important to regularly do this task as per the instructions provided in the link? Info - Working on creating a highly efficient production build... Note: Next.js now collects completely anonymous telemetry data on user usage. This data helps sha ...

Tips for populating an array with information gathered from an axios request within a React application

Currently, I am using axios to fetch data from an API and attempting to store the retrieved data in a variable that represents an array within the state of the component. However, when I try to do so, I encounter the following error: Objects are not valid ...

Property-based Angular Material row grouping in a mat-table is a powerful feature that enhances

Is there a way to organize the data in one row with the same ID? Currently, my data looks like this: Data Set: { "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": &quo ...

What category does React.js fall under - library or framework?

Hey there! I've noticed that sometimes people refer to React JS as a library, while others call it a framework. Can you shed some light on which term is more accurate? ...

Time when the client request was initiated

When an event occurs in the client browser, it triggers a log request to the server. My goal is to obtain the most accurate timestamp for the event. However, we've encountered issues with relying on Javascript as some browsers provide inaccurate times ...

Do not apply tailwindcss styles to Material-UI

I've been struggling to apply styling from tailwindcss to my MUI button. My setup includes babel and webpack, with the npm run dev script as "webpack --mode development --watch". tailwind.css module.exports = { content: ["./src/**/*.{js, jsx, t ...

What is the method for implementing an 'AND' condition in Firebase or its equivalent?

I have a query requirement where I am looking to display only specific data by using an 'AND' statement or its equivalent. To better explain, I am referencing the example given in the Firebase Documentation. // Find all dinosaurs whose height is ...

Is there a way to sort search outcomes by a drop-down menu in Next.js?

I am currently working on implementing a filter for my data based on selections made in a drop-down menu. Here's the setup: I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the di ...

Pseudo-element fails to display in React when applied to a paragraph tag, even with display block property set

I am experiencing an issue where the pseudo element ::after is not appearing in my browser. I am currently working with React.js and Material UI's makeStyles. Here is the code snippet causing the problem: modalTitle: { borderBottom: '2px sol ...

Discover the secrets to replicating the mesmerizing horizontal scrolling menu akin to the

What is the most effective way to create a horizontal menu similar to the innovative Google picture menu? Could someone kindly share their knowledge and provide the code for achieving the same outcome? ...

Utilizing auto-generated Nonce for Content Security Policy in a Node.js/Express web application

I've exhausted all possible solutions in my attempt to create a nonce and pass it successfully to the CSP and inline scripts with the nonce variable. Despite reading numerous articles, the guidance on accomplishing this task remains vague. Fortunately ...

Can you provide tips on using Ajax to store a cache file?

I've created a javascript/ajax function that retrieves a json file from an external server. The functionality I'm trying to implement includes: Fetching the json file from the external server Saving the json file on the local server Checking if ...

Is there a way to modify the dimensions of this container? (CSS)

After performing a search and clicking on a result, a white bubble pops up on the map. I am looking to use CSS to make this bubble smaller as it is currently too large. Can anyone provide guidance on how to achieve this? ...