Is e.preventDefault() failing to work in Next.js?

Hey everyone, I'm new to react.js and next.js. I attempted to copy some data from a form and display it in the console, but using e.preventDefault() is preventing me from submitting my form. Is there a more effective way to achieve what I'm aiming for? I opted for a simpler approach based on my understanding.

import Header from '../components/header'
import Navbar from '../components/navbar'
import React, { useState } from 'react'

export default function Home({data}) {
  
  const [form, setForm] = useState({})

const saveMovie = e =>{
    e.preventDefault()
    console.log("Why can't I see you?")
    console.log(form) // also not showing
  }  

  return (
    <div>
      { /* header */ }
      <Header />

      {/* Navbar */}
      <Navbar />

      {/*List of movies */}

          
<form className="form p-10 md:w-2/3 lg:w-1/2 mx-auto rounded" onSubmit={ saveMovie }>
     <div className="shadow">
       <div className="flex items-center bg-regalblue rounded-t-lg border-blue-500 border">
         <label  className="w-20 text-right mr-8 p-4 text-white">Title</label>
         <input  onChange={e=> setForm({...form, title: e.target.value})} type="text" name="title" id="title" placeholder="Enter movie title" className="flex-1 p-4 pl-0 bg-transparent placeholder-gray-600  outline-none text-white overflow-ellipsis overflow-hidden"/>
       </div>
       <div className="flex items-center bg-regalblue  rounded-t-lg border-blue-500 border">
         <label className="w-20 text-right p-4 mr-8 text-white">Year</label>
         <input  onChange={e=> setForm({...form, year: +e.target.value})} type="text" name="year" id="year" placeholder="Enter the year" className="flex-1  p-4 pl-0 bg-transparent placeholder-gray-600 outline-none text-white overflow-ellipsis overflow-hidden"/>
       </div>    
        <div className="flex items-center bg-regalblue rounded-t-lg border-blue-500 border">
         <label  className="w-20 text-right mr-8 p-4 text-white">slug</label>
         <input  onChange={e=> setForm({...form, slug: e.target.value})} type="text" name="slug" id="slug" placeholder="Enter the slug here" className="flex-1 p-4 pl-0 bg-transparent placeholder-gray-600  outline-none text-white overflow-ellipsis overflow-hidden"/>
       </div>       
       <div className="flex items-center bg-regalblue rounded-t-lg border-blue-500 border">
         <label  className="w-20 text-right mr-8 p-4 text-white">Description</label>
         <textarea onChange={e=> setForm({...form, description: e.target.value})}  type="textarea" name="description" id="description" placeholder="Enter the description" className="flex-1 p-4 pl-0 bg-transparent placeholder-gray-600  outline-none text-white overflow-ellipsis overflow-hidden"/>
       </div>
     </div>
     <button type="submit" className="bg-regalblue hover:bg-gray-900 block w-full rounded-md border py-4 text-white font-bold shadow">Submit Form </button>
</form>

      </div>
  )
}

Answer №1

My code is not triggering the handleSubmit function, despite my attempts to troubleshoot. I even went as far as reinstalling next.js, but unfortunately, that didn't solve the issue:

"use client"

import { useRouter } from "next/navigation"
import { useState } from "react"

export default function CreateForm() {
    
    const handleSubmit = async (e) => {
        e.preventDefault();
       
        console.log('submit')
    }

    return (
        <form onSubmit={handleSubmit} className="w-1/2">
            
            <button
                type="submit"
            >
                sendit
            </button>
        </form>
    )
}

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

Moment.js generated an error due to an unhandled promise rejection warning

I'm trying to determine if my current timestamp is equal or greater than a certain value, but I keep encountering errors. Here's my code with the error: {...} exports.validaforgotpass = async (req, res) => { {...} const results = aw ...

Is there a way to display the description field instead of the Id in a table using pxp-ui?

I am currently working with a table in pxp-ui and have implemented the following column: subsystemId: { type: 'AutoComplete', isSearchable: true, label: 'Subsystem Id', ...

Is there a way to dynamically fetch and run JavaScript code from the server without resorting to the use of the

In my current project, I am developing a unique PHP framework that empowers PHP developers to effortlessly craft ExtJS interfaces containing forms, grids, tabpanels, and menus exclusively through PHP classes. To illustrate, creating a TabPanel in this fra ...

Does the triple equal operator in JavaScript first compare the type of the value?

When using the triple equal operator, it not only measures the value but also the type. I am curious about the order in which it compares the value and returns false if they do not match, or vice versa. ...

Transforming iframe programming into jquery scripting

Currently, I have implemented an Iframe loading the contents within every 5 seconds. It works well, however, there is a consistent blinking effect each time it loads which can be quite bothersome. I am looking to replace the iframe with a scrolling div so ...

Is it a bad idea to set directive scope to false, considering the limitations on broadcasting in an isolated scope?

There is a unique situation I am trying to tackle where I need to use $broadcast within a directive's linking function that has an isolated scope. Unfortunately, broadcasting from inside an isolated scope becomes challenging as the directive scope doe ...

What could be causing the jQuery news ticker to malfunction on my site?

I recently made some changes to my main page by embedding HTML and adding the following code/script: <ul class="newsticker"> <li>Etiam imperdiet volutpat libero eu tristique.</li> <li>Curabitur porttitor ante eget hendrerit ...

Dynamically generating fields in JavaScript causes the fields to mysteriously vanish

Below is the JavaScript code I am working with: <script language="javascript"> function addInput() { document.getElementById('text').innerHTML += "<input type='text' value='' name='a1[]' size='60&a ...

Implementing Click-Activated Scroll-to-Div Feature in React

I need to implement a scroll-to-div feature in my React App. However, the current structure of my app is preventing me from passing refs as props correctly, making it challenging to utilize ref.current.scrollIntoView(). The layout of my code looks like th ...

Detecting Scroll on Window for Specific Element using Jquery

I need help troubleshooting my code. I am trying to activate only one item that comes from the bottom of the page, but instead all div elements are getting activated. $(window).scroll(function() { $('.parallax').each(function(e) { if($( ...

I'm interested in exploring different database implementation patterns in JavaScript. What kinds of approaches can I consider?

As someone who is relatively new to exploring JavaScript, I have been immersed in experimenting with a node test app and MongoDB. I am eager to delve into the database aspect of the app but finding myself uncertain about the most commonly used patterns in ...

When attempting to add a variable using the next() function, I encountered an error with the BehaviorSubject. The error message displayed was "this.count.next is not a function"

In my Angular service, there is a variable called count that I need to monitor for updates. Whenever this count variable is updated, I want to assign its new value to another variable in a separate component. import {BehaviorSubject} from "rxjs/BehaviorSu ...

How to invoke a function in an isolated scope of AngularJS using JavaScript

We are in the process of gradually switching our application to work with Angular. I have developed an angular module and a directive that aims to connect specific functionality to an HTML element. angular.module('myApp', [ ]) .controller(&ap ...

Encountering a Nextjs net::ERR_ABORTED 404 error while accessing the production server configured with

After successfully building and deploying my app locally without any errors, I encountered a frustrating issue when deploying it on the server. Every static file accessed at /_next/static/ resulted in a net::ERR_ABORTED 404 error. While the pages' HTM ...

Create a customized menu with jQuery that disappears when hovered over

Check out this menu I've created: http://jsbin.com/useqa4/3 The hover effect seems to be working fine, but I'm looking to hide the div #submenuSolutions when the user's cursor is not on the "Solution" item or the submenu. Is there a way to ...

Difficulty with deploying Next.js to Vercel due to restrictions on rate limits when utilizing getStaticProps()

In my Next.js project connected to Apollo, I have around 50 static URLs fetching data using getStaticProps(). The performance is great, and I enjoy how the pages load. However, a problem arises when Vercel builds the static versions of these pages during d ...

Easy methods to navigate between screens without using React Router libraries

After experimenting with two different methods to switch between screens in a simple application (up to 3 modes/screens), I am still in the learning phase and mainly focusing on practicing with useState and possibly useEffect for certain scenarios. I&apos ...

What is the best way to iterate through an array of objects in React and JavaScript, adding a new property to each object in order to generate a new array

Greetings, I am currently dealing with an array of objects structured as follows: const arr_obj = [ { children: [{}], type: "type1", updated: "somevalue", }, { children: [{}], type: ...

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...

Simulate a failed axios get request resulting in an undefined response

I'm having an issue with my Jest test mock for an axios get request, as it's returning undefined as the response. I'm not sure where I might be going wrong? Here is the component with the axios call: import {AgGridReact} from "ag-grid- ...