Uniqid in React fails to generate unique IDs

Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outside of the handleSubmit function, it works fine. Any insights on why this setup isn't functioning as expected would be greatly appreciated. Thank you!

import { useState } from 'react';
import Header from './components/Header';
import List from './components/List';
import React from 'react';
import uniqid from 'uniqid';

function App() {
const [todoList, setTodoList] = useState([]);
const [todo, setTodo] = useState({
name: '',
complete: false,
id: ''
});
const [error, setError] = useState(false);

function handleChange(e) {
setTodo({
  ...todo,
    name: e.target.value,
});
}

function handleAdd(newTodo) {
setTodoList([
  ...todoList,
     newTodo
])
}

function handleSubmit(e) {
e.preventDefault();
if (!todo.name) {
  setError(true);
} else {    
  handleAdd({
    ...todo,
       id: uniqid()
  })
setError(false);
setTodo({
  ...todo,
     name: ''
})
console.log(todo);
}
}

function handleDelete(id) {
const todoListItems = todoList.filter(todo => todo.id !== id);
setTodoList(todoListItems);
}

function handleClear() {
setTodoList([]);
}

Answer №1

It appears that the utilization of uniqid() is accurate. However, it's important to note that while setTodo will update the value of todo in the subsequent render of the component, any subsequent console.log(todo) within the same event block will still display the old value prior to the update.

To see a demonstration showcasing the unique ID generated, you can visit this live example: stackblitz

The above example also features modifications to both handleChange and handleAdd, ensuring that the previous value can be accessed without risking conflicts.

function handleChange(e) {
  setTodo((prev) => {
    return { ...prev, name: e.target.value };
  });
}

function handleAdd(newTodo) {
  setTodoList((prev) => [...prev, newTodo]);
}

In addition, a useRef has been included to clear the input field after submission. The original implementation reset the state value to "", but did not do the same for the input field.

import { useRef } from 'react';

function handleSubmit(e) {
  e.preventDefault();

  ...

  setTodo((prev) => {
    return { ...prev, name: "" };
  });
  newTodoRef.current.value = "";
}

We trust that these adjustments prove beneficial.

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

Turn off the perpetual active mode

I have a situation where a link maintains its active state after being dragged and released. This is causing an issue that I need to address. For example, you can see the problem here: http://jsfiddle.net/Ek43k/3/ <a href="javascript:void(0);" id="foo ...

Tips for avoiding duplicate Id tags while using Ajax in MVC

Hello everyone, I am curious to learn about the precautions and techniques you employ when working with Ajax or MVC functions such as @Html.Action in order to effectively manage and prevent duplicate Ids for Html tags. In addition, how does the page handl ...

What is the best way to make ng-style append to a pre-existing style?

I am facing an issue with my custom popover directive and another custom directive that uses it. I am attempting to use ng-style to adjust the width of the popover. Below is a code snippet from the directive's html template: <div my-custom-popover ...

Animate CSS Grid to dynamically fill the viewport on top of current grid elements

Please note that I am specifically seeking vanilla JS solutions, as jQuery is not compatible with this project I have a grid structure that is somewhat complex: body { margin: 0; height: 100vh; text-align: center; } .grid-container { ...

Redux - The same reducers, containers, and components are yielding varying outcomes

update: Issue resolved by connecting a different variable to the mapStateToProps. I'm encountering some challenges with my react-redux application and I'm struggling to pinpoint the error in my setup. You can access the source code here. The f ...

Activate the class when clicked

I am facing a minor issue with the JavaScript onClick function. I need a function that will target a specific class, like .modal. Currently, it looks like this <div class="modal" onclick="modalFix()"> <p>here is some text</p> </div> ...

Leveraging NextJS and React's Context API by incorporating a layout component wrapper

My current setup is as follows: I have a layout component where I include a navigation component and children. I enclose them within my Provider like this AppLayout.js <Layout> <Navigation/> <main> {children} </main> < ...

Iterating over an object and inserting values into a JavaScript object using the ascending count as the identifier

Illustration: { Are you a coffee drinker?: yes, Do you like to exercise regularly?: no, How often do you eat out at restaurants?: 3 times a week, What is your favorite type of cuisine?: Italian } Results: {yes: 1, no: 1, 3 time ...

Is it possible to modify the inactive color of just one radio button in Framework7?

Is there a way to change the inactive color of only one radio button in Framework7? I am aware that using the CSS variable --f7-radio-inactive-color allows me to set the inactive color for all radio buttons. However, I specifically want to modify the inac ...

Troubleshooting: jQuery.load function not functioning properly within ASP.NET MVC

I'm facing an issue with my code setup. Currently, I have the following components in different files: @Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html"))) This is included in my Razor file. <li><a href="#">Personal Re ...

I'm experiencing an issue with Gravity Forms validating hidden fields, is there a solution for this problem?

On my webpage, there are four fields labeled A, B, C, and D. Each field has its own set of conditional logic that determines whether it should be visible or hidden. Let's say a user lands on this page and only field B is displayed while the others are ...

Arrange the table by adding and editing before and after appending

I have a table data that needs to be dynamically appended. But I want to allow users to add new data using text input and also edit the existing data before and after it's appended. The problem is that when I append new data, it overwrites the previo ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

Javascript function failing to execute upon page load

I don't have much experience with JavaScript, but I found the following code in a .htm file. The function doesn't seem to be triggering when it should; It is supposed to activate when the page is directly opened i.e www.site.com/12345.htm This ...

Is it possible to automatically mute an HTML 5 video when closing the modal?

Is there a way to pause a video that plays in a modal and continues playing in the background when the modal is closed? I am using the Materialize library. <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <!-- Compiled ...

verifying the presence of a string or value within an array

I'm currently working on a feature that involves adding an element to an array by typing something into a text field and clicking a button. I've also implemented an if statement to check if the input already exists in the table, and show an alert ...

Leveraging LevelGraph with MemDOWN

I've been experimenting with using LevelGraph and MemDOWN together, but I've noticed that my put and get queries are significantly slower compared to using the filesystem directly with LevelUP. It seems like there might be some mistake in my setu ...

Player script does not contain a valid function signature according to XCDYouTubeKit

I need help finding a regular expression to match these Youtube links. I'm feeling lost and unsure of what to do. https://www.youtube.com/watch?v=2BS3oePljr8 http://www.youtube.com/watch?v=iwGFalTRHDA http://www.youtube.com/watch?v=iwGFalTRHDA& ...

"Root exit status cannot be determined." encountered in a Next.JS application

Encountering an issue with a NextJS app? The error arises from the following code snippet, specifically this line: const theResult = await audioChunks(chanlID) // This leads to an error !! This particular line is causing trouble as indicated. The error d ...

Update the text on the form submit button after it has been submitted

Is there a way to change the text on a submit button after it has been clicked? I have a form with a button and I want to switch the text from "click" to "Next" once the form has been submitted. <form> <div class="form-grou ...