Issue with Next.js Button not displaying expected result

I am in the process of developing a todo list application using next.js. The issue I am facing is that when I input data into the field, it correctly displays in the console. However, upon clicking the button, instead of the input displaying like a normal todo list app, the page just reloads. I need assistance with resolving this problem.

import Link from 'next/link'
import Head from 'next/head'
import Script from 'next/script'
import { useState } from 'react'



export default function FirstPost() {
const[userInput,setUserInput] =useState('')
//create state props
const[todoList,setTodoList] =useState([])
const handleChange = (e) =>{
    e.preventDefault();

    setUserInput = (e.target.value)
    console.log(setUserInput)
}

//handling submit
const handleSubmit =()=>{
e.preventDefault
setTodoList({
  SetUserinput,
  ...todoList

})

}

  return (
    <>
    <Head>
    <title>Todo List</title>
    </Head>
 
    
    
    <h1>TodoList App</h1>
    <form>
        <input type="text" onChange={handleChange}/><button onClick={handleSubmit}>Submit</button>
        </form>
     <ul>
       {
       todoList.length>=1 ? todoList.map((todo,idx) =>{
         return <li key={idx}>{todo}</li>
       })
       :'Enter a Todo Item'

      }
     </ul;


        <h2>
        <Link href="/">
          <a>Back to home</a>
        </Link>
      </h2>
      
      
    </>
    
  )
}

Answer №1

//taking care of submission
const submitHandler =()=>{
e.preventDefault
setList({
  setInput,
  ...list

})

Ensure to pass the argument e to the function, as you had missed including it. Modify the code like this:

//taking care of submission
    const submitHandler =(e)=>{
    e.preventDefault
    setList({
      setInput,
      ...list
    
    })

Answer №2

After some troubleshooting, the error has been resolved successfully

Here is the updated code:

import Link from 'next/link'
import Head from 'next/head'
// import Script from 'next/script'
import { useState } from 'react'

export default function Todo() {
  const[userInput,setUserInput] =useState('')
  //create state props
  const[todoList,setTodoList] =useState([])
  const handleChange = (e) =>{
      e.preventDefault();
      setUserInput(e.target.value)
      console.log(userInput)
  }

  //handling submit
  const handleSubmit =(e)=>{
    setTodoList([...todoList,{elt:userInput}])
    console.log(todoList)
    setUserInput(' ')
  }

  //delete functionality
  const handleDelete =(todo)=>{
    const updatedArr = todoList.filter(todoItem=> todoList.indexOf(todoItem) != todoList.indexOf(todo) )
    setTodoList(updatedArr)
  }

  return (
    <>
    <Head>
    <title>Todo List</title>
    </Head>
    <h1>TodoList App</h1>
        <input type="text" placeholder="enter a todo item"value={userInput} onChange={handleChange}/>
        <button onClick={handleSubmit}>Submit</button>
     <ul>
       {
         todoList.length>=1 ? todoList.map((todo,idx) =>{
           return <li key={idx}>{todo.elt}<button onClick ={(e) =>{
             e.preventDefault()
             handleDelete(todo)
           }}>Delete</button></li>
         }) : 'Enter a Todo Item'
       }
     </ul>
        <h2>
          <Link href="/">
            <a>Back to home</a>
          </Link>
        </h2>
    </>
  )
}

An interactive todo list application with basic functionality and no styling applied yet.

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 issue arises when attempting to make an Ajax request after changing the value of a cascading dropdown

Hey there! I'm currently working on a cascading drop-down feature where, upon change, I need to populate another field with data from the database. Unfortunately, every time I try to populate the drop-down, my AJAX call returns an error 500. I can&ap ...

Issue with Three.js: GLTF model not positioned correctly at origin point

After attempting to load a glTF model with a 0,0,0 position, I noticed that it appears far from the origin. Upon trying to rotate the glTF model, I observed that it spins around (indicated by blue dots) the origin instead of spinning from its center. Thi ...

Open the iframe link in the main window

As a newcomer to this platform, I am trying to figure out how to make a link open in the parent page when clicking a button within an iframe. Currently, my code opens the link in a new window. <html> <body> <form> <div class ...

Using JQuery to monitor the loading of a newly selected image src attribute

As a newcomer to JavaScript and JQuery, I am facing a challenge that I couldn't find a solution for in other discussions: I have a function that retrieves the path to an image (/API/currentImage) using a GET request and needs to update the src attrib ...

The accuracy of real-time visitor numbers in Google Analytics is often unreliable

My website uses Google Analytics to track the page chat.php. The code snippet is correctly placed on the page according to the documentation. Within this page, there is a Flash object that connects users to an IRC chat room. Currently, there are 50 unique ...

Exploring the utility of promise.race()

When it comes to promise, there are two main options that I am aware of: promise.all() promise.race() I have a good grasp on what promise.all() does. It runs promises simultaneously, and upon successful resolution, the .then method provides you wit ...

The material-ui library always registers Event.ctrlKey as true

When using the Table Component from the material-ui library, I encountered an issue with the multiSelectable feature. Setting the value of multiSelectable to true allows for multiple selections, but the behavior is not what I expected. By default, the sel ...

Utilizing Array.from with a XPathResult: A Comprehensive Guide

In my sample document, I found 138 nodes with the tag td using querySelectorAll. Array.from(document.querySelectorAll('td')).length 138 However, when I tried to do the same using XPath, I did not get any result: Array.from(document.evaluate(". ...

What methods are available for updating the href color of an element using the DOM?

I am looking to update the color of a tab (Mathematics-tab) based on the value of 'aria-selected' changing to true in Bootstrap. I have multiple tabs, including one for mathematics, and I want to visually differentiate between selected and unsele ...

iPad problem resolved: Disable click hover and double-click issue

I'm experiencing a problem with my web application specifically on Safari for iPad. I have to click twice in order to actually perform the click on the <a> tag. The first click triggers a hover effect, similar to when you hover with a mouse on d ...

Choose an image and save the selection information for the following page (Tarot card)

I'm in the process of creating a website that showcases multiple tarot cards. The goal is for users to select the cards they're interested in and have their chosen card displayed on the next page. I've implemented some code for selecting the ...

Tips for disabling viewport resizer while accessing the Console panel in Chrome using Control+Shift+J

Currently, I am utilizing the viewport resizer in Chrome to preview how my code appears on various devices. However, I have encountered an issue - whenever I try to access the console using ctrl + shift + j, the viewport resizer opens instead. You can obs ...

Adjusting Text Size Depending on Width

I recently used an online converter to transform a PDF into HTML. Check out the result here: http://www.example.com/pdf-to-html-converted-file The conversion did a decent job, but I'm wondering if it's feasible to have the content scale to 100% ...

encountering an issue with the react hook useHistory leading to an error

I recently encountered an issue while implementing useHistory() in my code. Previously, I had used it without any errors, but now I'm getting the following error in this component: Line 6:18: React Hook "useHistory" is called in function "showPost" ...

Determine the most recent API response and disregard any outdated responses from previous calls

I am currently working on a search page where the user can input text into a search box. With each character they enter, an ajax call is made to update the UI. However, I am facing an issue in determining the response from the last API call. For example, i ...

Difficulty transferring form information to PHP utilizing Ajax

Originally, I had a traditional HTML form that submitted data through a button, redirecting the user to the page where the PHP code ran successfully. Now that everything is functioning as expected, I aim to pass the form variables to PHP using Ajax in ord ...

Vue.js versatile form for both adding and editing

As a newcomer to the world of vue.js, I am currently working on expanding some tutorials that I have completed. After struggling with this for three hours now, I must admit that I am feeling quite frustrated. Just to give you a heads up, I am using firebas ...

Optimizing HTML and Script loading sequences for efficient execution

I have a query regarding the loading order of scripts in web browsers. I am interested in knowing the most efficient way to redirect users to a mobile website on the client side. For example, if I place a mobile detection script within the <head> se ...

Display problem with Backbone view

I'm having trouble loading views on my page while using underscore for templating. I've tried navigating to the page and loading the view in the initialize function, but neither approach has worked. The majority of this code is from an example. ...

extracting array index from a Mongoose array

//index.js let countryNameList = { "name"=["Bangladesh","India","Australia"] } //Output Section let findCountryIndex = awaitDataModel.find({$indexOfArray:{CountryName:"Bangladesh"}}) console.log(findCountryIndex); //Expecting Output : 0 I am l ...