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

JavaScript string manipulation function

Hey everyone, I need help finding a one-line solution in JavaScript to determine if a string contains a semicolon without using a loop. If anyone knows how to do this, please share your knowledge! ...

The use of '-' in v-bind:style within Vue.js

I'm having trouble figuring out how to use CSS code with dashes in v-bind:style. When I attempt something like this: <DIV style="width:100px;height: 100px;background-color: red;cursor: pointer;" v-bind:style="{ margin-left: margin + 'px' ...

Utilizing mutation observers for monitoring dynamic changes in fetch request outcomes

I'm currently developing a specialized interface that showcases the cumulative ticket count (an integer representing the total) sourced from a 3rd party API. My goal is to trigger a notification whenever this count increases. I've come across inf ...

JavaScript: A step-by-step guide to extracting the file name and content from a base64 encoded CSV

I have a base64 string that was generated by encoding a csv file, const base64 = 'LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNDc2MDgwNjM5MTM4ODk4MTc2NTYwNA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJmaWxlIjsgZmlsZW5hbWU9ImNoYXJ0T2ZBY2NvdW50LmNzd ...

After Effects Script: Apply various character styles from main text to subtext

I'm currently working on an After Effects script that can transfer the style and text of a text layer to another text layer in a different comp. The script works perfectly if the parent text layer only has one style, but I need it to handle a situatio ...

The Next.js application is functioning perfectly in the development environment. However, an error is encountered when running `npm run build

Encountering an error during the build process of my Next.js app. Generating static pages (0/20) [= ]TypeError: u is not a function at m (C:\Users\coool\Documents\AnalyticsBrewery\analytics-brewery-a1\.next\server&bso ...

Invoking a static method within a cshtml document

I am currently working on implementing a clickable DIV within a vertical tab panel. My goal is to have a specific static method called when the DIV is clicked. Here is what I have done: <div class="tabbable tabs-left"> <ul class="nav nav-tabs"> ...

Is there a way to transmit the ENTER key press to the page setup dialog within Internet Explorer 7?

My code is designed to change the page orientation. It functions correctly in IE6, but encounters issues in IE7. Specifically, it stops at %a and fails to input the enter or tab keys needed to press 'OK'. var shell; function SetPrintProperties() ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

Issues with Tailwind styles arising when deploying and using Windows Subsystem for Linux (

While developing with Next.js + Tailwind + DaisyUI on a Mac, everything looks great and works as expected. However, when I switch to WSL, the styles appear broken and different from what I intended. The same issue occurs when I deploy my site on Vercel. Do ...

Dynamically implementing event listeners in JavaScript to remove specific elements based on their

My website has a list of phones displayed as ul li. When a user clicks the "Buy" button, it should create a new li within another div called "ordersDiv". Users can delete their purchase from the cart by clicking "Remove", which should remove the li with ma ...

When a block is clicked, jQuery will reveal that block while hiding the others sequentially, starting with the second block, then the third, and finally the fourth

Creating a navigation menu with 4 blocks can be a bit tricky, especially when trying to show one block at a time upon click. Here is my code attempt, but unfortunately it's not working as expected. I would greatly appreciate any help or suggestions on ...

"Including Span icons, glyphs, or graphs within a table cell in AngularJS based on a specified condition or numerical

I'm attempting to incorporate span icons/glyph-icons using Angular within a td before displaying the country. I've utilized the code below to achieve this, but I'm looking for a more dynamic and elegant solution. Your assistance is greatly a ...

Utilize an external JavaScript file function within an AngularJS controller

I have an external JavaScript file with additional functions that I am trying to call from an Angular controller. Here is an example of the external.js file: ... ... function fun() { ... ... } ... ... The controller in question is called acccountCon ...

The function Sync in the cp method of fs.default is not a valid function

When attempting to install TurboRepo, I encountered an issue after selecting npm. >>> TURBOREPO >>> Welcome to Turborepo! Let's get you set up with a new codebase. ? Where would you like to create your turborepo? ./my-turborepo ...

Issue with Next-Auth getServerSession failing to fetch user data in Nextjs 13.4 API Route

Having an issue with accessing user session data in a Next-Auth/Nextjs 13.4 API Route. I've set up the JWT and Session callback, but the user data defined in the callback function isn't translating correctly to what getServerSession is fetching i ...

Incorporate fresh Google sites into different web pages using iFrame integration

Wishing you a fantastic day! I am currently working on embedding a brand new Google site into another webpage. I attempted to use an iframe for this purpose, but unfortunately it did not work as expected. Here is the code snippet: <iframe width="1280 ...

What sets apart optionalDependencies from peerDependencies in the Meta optional?

Why are both marking dependency as optional and what is the specific use-case of each? Is peerDependenciesMeta intended for npm packages while optionalDependencies is meant for projects? For example, in my npm package, certain modules require dependency ...

The React useEffect hook runs whenever there is a change in the state

Within my React component, I have the following code snippet (excluding the return statement for relevance): const App = () => { let webSocket = new WebSocket(WS_URL); const [image, setImage] = useState({}); const [bannerName, setBannerName] = use ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...