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

Time:11-10

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;
  }
} ));

CodePudding user response:

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
}
  • Related