skip to Main Content

I’m developing a pomodoro Task App in React JS. I have an array which it called "task", I’m using "useState" hook. I have no problem with adding new "task". But when I try to delete an element from this array, my function do nothing.

const [tasks, setTasks] = useState([]);

Add Element function

function addTask(data) {
  if (tasks.length === 0) {
    setTasks((task) => [
      ...task,
      {
        name: data.name,
        description: data.description,
        selected: true,
        duration: data.duration,
        pomodoros: data.pomodoros,
      },
    ]);
    return;
  }
  setTasks((task) => [
    ...task,
    {
      name: data.name,
      description: data.description,
      selected: true,
      duration: data.duration,
      pomodoros: data.pomodoros,
    },
  ]);
  return;
}

Delete Element function

function deleteTask(index) {
  let currentName = tasks[index].nombre;
  setTasks((current) => current.filter((task) => task.name !== currentName));
}

I pass an index to this function as an argument, then match the current name of the object of the array with the correct element name in my array.
I print "task" array but it looks like nothing change.

I’m expecting an answer explaining it

2

Answers


  1. Looking at your example code, In your delete function on your first line, you call for a item that does not exist within the array.

    To be specific:

    let currentName= tasks[index].nombre
    

    And looking at your set example, you are using:

    name : data.name
    

    when setting.

    I also noticed your trying to filter against names. I recommend you creating some sort of unique identification number, if you ever have tasks that have the same names.

    Login or Signup to reply.
  2. As highlighted by David and Fady, the issue is most likely from .nombre as there is no such key which exists and hence your filter method returns the array as it is.

    From the intention of functions, the code snippet look good to me.

    However, you may refer to this StackBlitz for your reference. I have tried to create a very generic react app which showcases the behaviour explained above.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search