Yeo Bryan
Yeo Bryan

Reputation: 431

Using If-else instead of ternary operator in map function to set state

The objective of the function is to toggle the reminder property of the task object when the task is being double clicked.

I am trying to create other similar functions to replace the tutorial code such as instead of using map, I would instead use a for loop. However, upon trying to use if-else condition within the map rather than ternary operators the state of the task ends up being undefined. Can someone tell me what is wrong with my code?

Tutorial Code (Working)

setTasks(tasks.map((task) => 
  task.id === id ? { ... task, reminder : !task.reminder} : task
));

For Loop Variation (Working)

let tempTasks = [];
for(let i = 0; i < tasks.length; i ++){
  if(tasks[i].id == id){
    let newObj = {};
    newObj['id'] = tasks[i].id;
    newObj['text'] = tasks[i].text;
    newObj['day'] = tasks[i].day;
    if(tasks[i].reminder === true){
      newObj['reminder'] = false;
    }
    else{
      newObj['reminder'] = true;
    }
    tempTasks.push(newObj);
  }
  else{
    tempTasks.push(tasks[i]);
  }
}
setTasks(tempTasks);

Map Variation Using If Else ( Not Working )

setTasks(tasks.map((task) => {
  if(task.id === id){
    task.id = task.id;
    task.text = task.text;
    task.reminder = true;
  }
  else{
    task = task;
  }
} ));

Upvotes: 0

Views: 268

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

need to return the object.

setTasks(tasks.map((task) => {

  if(task.id === id){
    task.id = task.id;
    task.text = task.text;
    task.reminder = true;
  } 

 return task
}

Upvotes: 1

Related Questions