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

The persistent Bulma dropdown glitch that refuses to close

In the project I'm working on, I have implemented a Bulma dropdown. While the dropdown functions correctly, I am facing an issue when adding multiple dropdowns in different columns with backend integration. When one dropdown is open and another is cli ...

unable to adjust the maximum height limit

I've been struggling to set a maximum height on the slider I'm currently using. No matter what height value I input, it doesn't seem to take effect. Additionally, I attempted setting the width for the echo img row in the PHP section but enco ...

Strange Actions with JQuery Drag-and-Drop Functionality

Apologies for my limited experience with JQuery UI, but I am in the process of creating a web-based chess engine for 2 players using JavaScript. Instead of point and click, I have decided to implement a user-friendly drag and drop feature for non-mobile us ...

Display Angular errors specifically when the input field is filled out and contains invalid data

I need help with toggling an error area on my form so that it only appears once there is input. It seems unnecessary for errors to show up if the user hasn't even started typing. <form name="registerForm"> <input type="email" name="email" ...

Vue.js is unable to dispatch an event to the $root element

I'm having trouble sending an event to the root component. I want to emit the event when the user presses enter, and have the root component receive it and execute a function that will add the message to an array. JavaScript: Vue.component('inp ...

How can we transfer functions between files in JavaScript when creating a service library?

There's a piece of code located in my identity service that I'm working with. export function sumbitLogin(username, password) { console.log(username, password); } I want to simplify the process of accessing services in my components without ...

Reorganizing array of objects in JavaScript

Currently, I am tackling a challenge within a ReactJS application. My task involves extracting JSON data related to various products and restructuring this information for the purpose of categorization and displaying it accordingly. Despite my attempts wi ...

Is there a way to utilize JSON parse for converting deeply nested keys from underscore to camelCase?

A JSON string containing an object is on my mind: const str = `[{"user_id":"561904e8-6e45-5012-a9d8-e2ff8761acf6","email_addr":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa0a3a6a5bc8aaca ...

Is it possible to use JavaScript to load, edit, and store text files?

Hey there, I have a text file that needs some find and replace operations done on it within the browser. My coding skills are still in the beginner stage, so creating web apps from scratch feels overwhelming right now. All I want to do is upload the file, ...

Can the keypress event be modified within the Google Chrome browser?

My code is functioning in IE but not in Chrome. I am having issues with the event not changing. Is there a different method for achieving this in Chrome, rather than assigning specific values to the charCode, keyCode, and which variables? You can view my ...

``Is there a way to redirect users when they click outside the modal-content in Bootstrap

I have a modal on my website that currently redirects to the homepage when the close button is clicked. However, I also want it to redirect to the homepage when clicking outside of the bootstrap modal, specifically targeting the ".modal-content" class. I ...

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

Guide on accessing an array within a JSON object?

I have the following JSON object: [ { "comments": [ { "created_at": "2011-02-09T14:42:42-08:00", "thumb": "xxxxxxx", "level" ...

Unable to redirect page in Codeigniter after submitting button

I am facing an issue with inserting and updating data in my database using Ajax to my controller. Despite the data being inserted and updated accurately after clicking the button, the changes are not reflected on my view page until I manually refresh it. A ...

How can we manage a discovered item in Promise and Recursion scenarios without relying on a callback function?

I need to iterate asynchronously and recursively over a folder hierarchy on the server. When a file is found, I want to call a custom method. Here's my current code structure: searchFile(root, handleFile); // recursively loop through folders and ha ...

What are the steps for implementing middleware that relies on a socket connection?

Using express.io, I am currently working on creating a middleware that necessitates a connection to a remote server through two sockets. However, I have encountered an issue. var net = require('net'); module.exports = function (host, port) { ...

Guide on how to incorporate an external javascript file into an HTML button

I am currently working on an exercise through Udacity that involves creating an HTML form with JavaScript functions. The task is to input text into the form, submit it, and have it displayed on the webpage within a blue square. This exercise is designed to ...

Stopping a NodeJs file running on an Ubuntu server

After enlisting help to install a Js script on my server, I encountered an issue where changes I made to the scripts/files were not reflected in the browser. After scouring the internet for answers for about 24 hours, I discovered that Js scripts need to b ...

Encountered an issue while trying to use Figma's spellchecker extension

Despite following the instructions in the readme carefully, I am facing difficulties running the Figma spellchecker extension. Executing npm run build goes smoothly. But when I try to run npm run spellcheck, I encounter an error message in the console: co ...

Trouble with using $.ajax to call a PHP function

Hey everyone, I hate to ask for help but I'm really stuck on this issue. I've tried everything and followed all the scenarios on this site, but I just can't seem to get it working. I even added alerts and echoes, but the function doesn' ...