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

Implementing TypeScript with styled components using the 'as' prop

I am in the process of developing a design system, and I have created a Button component using React and styled-components. To ensure consistency, I want all my Link components to match the style and receive the same props as the Button. I am leveraging t ...

Utilizing jQuery for AJAX requests triggered by mouse movement

I have a project where I am creating an image with gdimage, consisting of 40000 5x5 blocks that link to different user profiles. My goal is to implement a feature where hovering over one of these blocks triggers AJAX to fetch the corresponding user profile ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Constructing Browserify with dependencies containing require statements within a try-catch block

When attempting to integrate timbre.js (npm version) with Browserify, I encountered an issue where require statements for optional dependencies were enclosed in a try statement (check the source here). This resulted in a browserify build error displaying: ...

Display the number of rows per page on the pagination system

Looking for a way to add a show per page dropdown button to my existing pagination code from Mui. Here's the snippet: <Pagination style={{ marginLeft: "auto", marginTop: 20, display: "inline-b ...

Discover the method for tracking idle time with jQuery and PHP

I have a script that utilizes PHP sessions through a custom class. One of the methods in this class calculates the remaining seconds before the session expires. Whenever the user refreshes the page or opens a new one, the idle time counter is reset using ...

I am experiencing an issue with my react-dates DateRangePicker as it is not functioning/rendering properly

As I work on developing a react redux expense tracking application, I am facing an issue with moment.js and react-dates for setting time and filtering the time range. Whenever I select anywhere or click the "x" to clear the date, nothing appears on the scr ...

A step-by-step guide on bringing in objects in JavaScript and Node.js

Let's say we have a file called main2.js exports.obj = { x: 10, setX: function(y) { this.x = y; }, getX: function() { return this.x; } }; Now, we also have two other files: abc.js const obj = require("./main2").o ...

Personalized Pop-up Notification Upon Exiting Chrome Tab

I'm trying to implement a custom modal window that appears when the user attempts to close the Chrome Tab where my app is running by clicking the X button, displaying a message asking "Are you sure you want to close?". However, despite my efforts, I a ...

The challenges of positioning HTML li elements in a floating layout

Check out my website: . I'm having an issue with the layout where two <li> elements are stacked on top of each other and one is floating next to them, but it's only floating next to the second one. How can I make it float next to the first ...

Ways to retrieve the path of a button found within table cells

https://i.stack.imgur.com/pUYHZ.jpgI'm currently working on a table where I've created a button that's being used in various rows and tables based on certain conditions. There's a specific scenario where I need to display the button for ...

Verify that the zip code provided in the input matches a record in the JSON data and extract the

I need to create a feature where users can input their zip code, check if it matches any of the zones in a JSON element, and then display the corresponding zone: var zones = [{ "zone": "one", "zipcodes": ["69122", "69125", "69128", "69129"] }, ...

Error in the Angular-UI calendar

I'm encountering an issue while trying to set up the angular-ui calendar. When I run it, I get the following error: TypeError: undefined is not a function at Object.eventsWatcher.onChanged (http://localhost/fisioGest/js/calendar.js:262:41) Despite b ...

Exploring the potential of HTML5 canvas for speedy pixel manipulation

Is there a method to interact with canvas pixels in real-time without using getImageData or createImageData due to their slow performance? ...

When the VueJS element is rendered on Chrome addon, it suddenly vanishes

I have been using a developer mode addon successfully in Chrome for quite some time. Now, I want to add a button to my Vue-powered page. Here's the code snippet: let isletCtl = document.createElement('div') isletCtl.id ...

The MDX blog was set up to showcase markdown content by simply displaying it without rendering, thanks to the utilization of the MDXProvider from @mdx-js/react within Next JS

I'm currently in the process of setting up a blog using MDX and Next.js, but I've encountered an issue with rendering Markdown content. The blog post seems to only display the markdown content as plain text instead of rendering it properly. If y ...

Exploring JavaScript functions within the Rails 4 asset pipeline directory

I am facing an issue while trying to use a JavaScript function through the Chrome Console after embedding that function within the Rails Asset Pipeline Manifest. To achieve this, I followed these steps to create and set up a basic Rails 4.2.4 App: $ rails ...

"Error encountered: 'require' is not defined in the bundled JS file for

Recently, I decided to try my hand at Django and ReactJS. While attempting to compile a simple JSX code to JS, I followed this tutorial: . However, I encountered an error that prevented it from working. I then resorted to using npm run dev to compile the c ...

Conceal a row depending on the value in a specific column

After reviewing the data in the table provided: +-----------------------+-----------------+---------------+ | 212 | fred | red | +-----------------------+-----------------+---------------+ | 230 ...

Tips on using the Hover property in CSS for an element that includes both :after and :before properties

I've created a hexagon using CSS after and before properties, and now I'm attempting to add a glowing effect around the hexagon when hovering. It works perfectly for the center of the hexagon but not for the top and bottom points of the shape. ...