encountering an issue with the map function being undefined

I am currently working on a todo list and I want to be able to delete data stored in an array using the filter method. However, I am encountering an error with my code. Here is the snippet:

const onDelete = (id) => {
    setaddItem((prevData) => {
        console.log(prevData);            
    });
}            

I am trying to implement it like this:
const onDelete = (id) =>{
       setaddItem((prevData) =>{
          prevData.filter((value, index) =>{
              return index !== id;
           })
       })}

I'm not sure why I am getting this error. Can someone please help me troubleshoot? Below you can find the complete code for my todo list:

function App() {
  const [addItem, setaddItem] = useState([]);
  
  const addNote = (note) => {
    setaddItem((prevData) => {
      console.log(prevData);
      return [...prevData, note];
    });
  };
  
  const onDelete = (id) => {
    setaddItem((prevData) => {
        console.log(prevData);
    });
}
    
return (
<>
  <Header />
  <CreateNote passNote={addNote} />
  {
    addItem.map((val, index) => {
      return (
        <Note
          key={index}
          id={index}
          title={val.title}
          content={val.content}
          deleteItem={onDelete}
        />
      );
    })}
  <Footer />
</>
);
}
export default App;

I am facing an issue with my todo list where the 'addItem.map' function is not being recognized. Any guidance on how to resolve this would be greatly appreciated. Thank you!

Answer №1

Attempt modifying the onDelete function in the following manner:

const onDelete = (id) => {
  const filteredItems = [...itemsList].filter((item, index) => index !== id);
  setItemsList(filteredItems);
};

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

What is the right way to nest a SCSS rule for a specific selector within a list using the "&" symbol?

I have a question that I couldn't find the answer to in any documentation or on Stack Overflow. While this example may not be perfect, it should give you a basic understanding of what I'm trying to achieve. Illustration .btn-group { .btn ...

Reposition the CSS content

In order to achieve the desired effect of having the text in the middle of the div both vertically and horizontally, you can try using the following code: .servicecircle { width: 204px; height: 204px; background-image: url('secret.png&a ...

The properties of the NextFont variable cannot be utilized in the CSS global scope when using the var() function

// font.ts file import { Quicksand, Syncopate } from 'next/font/google'; export const quickSandRegular = Quicksand({ subsets: ['latin'], variable: '--font-quicksand-reg', weight: '400', display: 'swap& ...

Firefox animation causes text to flash intermittently

I am looking to create a slide animation using CSS and AngularJS. I have made progress with this example: JSFiddle. The animation works smoothly on Chrome, but on Firefox, the text shakes and flickers slightly during the animation. I am struggling to pinpo ...

What is the best way to link multiple select tags in an HTML document?

I am working with a data grid that contains student information such as Name, Class, and Score. Each row has a checkbox for selection. The requirement is that when the user selects one or more rows and clicks on the "show information" Button, a new windo ...

Is there a way to determine if jQuery lightslider has been initialized, and if so, how can I effectively remove the instance?

Currently, I have integrated the JQuery lightSlider into my project. Despite some code adjustments, it is functioning well. My goal is to dynamically replace the lightSlider content with data returned via AJAX, which I have successfully achieved. After r ...

When setting the defaultChecked value in React, it will be true if the corresponding key value in the object

Looking at the dataset I have, it includes the amenities field which is an object within another object: { name: "California Maki Resort", price_per_night: 2804.0, description: "On a lush 16-hectare island with white-sand beaches, this re ...

I encounter a CORS issue on Heroku, but strangely it only occurs after 20 minutes of deploying. Prior to that time frame, everything functions seamlessly

Today, I encountered a strange issue while hosting my first Node JS backend on Heroku. Everything runs smoothly when I register/login immediately after deploying the backend. However, if I try to register/login after about 15 minutes, I start receiving a C ...

Checking if the group of radio buttons has been selected using JQUERY

Need help with validating a group of radio buttons. If none are checked, display an error message in the span element to prompt users to select an option. The strange issue I am facing is that the validation code works only when placed below the radio butt ...

Dealing with a jQuery/JavaScript issue involving thumbnail images

I am facing an issue with smooth transitions between thumbnail images in HTML list tags. I have Jquery listeners set up for mouseenter and mouseleave events that update a parent image when a thumbnail is hovered over. The problem arises when scrolling fro ...

The reveal/conceal feature will not reveal all elements at the outset

I've been working on implementing a show/hide elements filter. However, I'm facing an issue where all elements that are supposed to display initially are hidden instead. Additionally, the 'active' class is not being properly removed or ...

Tracking User Visits in Codeigniter

Below is the code breakdown: (Step by step) Place counter.txt in APPPATH . 'logs/counter.txt' Set up counter_helper.php in APPPATH . 'helpers/counter_helper.php'; Autoload the newly created helper in APPPATH . 'config/autoload.p ...

Why are the UI components (`Card Number`, `MM/YY`, `CVC`) not being displayed in the React app when using Card

Having an issue where the CardElement Ui component is not visible in the image provided. It should appear above the Order Total: $0 next to the payment method. https://i.sstatic.net/NCK5z.png I've attempted various debugging methods without success. ...

Verify whether all the elements within a specific div are distinct by utilizing jQuery

I need to create a select box that, when an option is chosen, generates a certain number of textboxes within a div. Currently, there are three fields: display_name[], user_name[], and user_password[] The code for this functionality is as follows: <se ...

Column spacing and size manipulation with Bootstrap 4

I'm currently facing an issue with aligning elements and spacing them correctly in my project. How can I resolve this using only the col class and Bootstrap 4, without resorting to CSS? I have attempted various margin spacing options like ml-md-4 and ...

How to Set Focus on React Element Dynamically Without Using an Arrow Function

I have recently been working on a code snippet that is performing very efficiently: import React, { RefObject, useReducer, useRef, useState } from 'react'; import TextField from '@material-ui/core/TextField'; const MyComponent ...

Mastering various techniques for creating styles with makeStyles in React JS Material-UI

As a newcomer to React JS and Material UI, I am experimenting with creating various styles of buttons. Each button should have a unique appearance based on attributes like name= submit, ok, cancel, confirm, alert. App.JS import CssButton from './con ...

Online platform generating printed code

Have you checked out the website here? I'm facing a problem on that site and can't figure out why. I've installed PDO, PHP, httpd, php-mysql, but still unable to resolve the issue. I've even tried reinstalling everything and following ...

Creating a dynamic 3x3 layout using flexbox: a step-by-step guide

Is it possible to dynamically create a layout in Next.js with 3 columns of 3 rows using flexbox, React Bootstrap, or CSS only? https://i.sstatic.net/tTinS.jpg ...

What is the impact of a floated element on vertical spacing?

I have come across an article discussing the usage of CSS, but I am puzzled as to why image number four is not positioned below image number one. Instead, it appears below image number three. Can someone please explain this to me? Here is the HTML code sni ...