Kaleem Nalband
Kaleem Nalband

Reputation: 697

Removing a object from array state ReactJS

I have a functional component, in that i have a array state with object as items. now i wanted to remove an item at particular position.

const [tasks, setTasks] = useState([
    { project: "aaaa", task: "xxxxx", status: true },
    { project: "bbbb", task: "yyyyz", status: true },
    { project: "cccc", task: "zzzzz", status: true }

  ]);

  function addTask(task) {
    setTasks(oldArray => [...oldArray, task]);
  }

  function deleteTask(pos) {
    let _tasks = tasks;
    _tasks.splice(pos, 1);
    setTasks(_tasks)
  }

here the task is get deleted but UI is not updated untill i add a new item to state array.

Upvotes: 2

Views: 33

Answers (1)

codemonkey
codemonkey

Reputation: 7905

This won't create a copy of your state variable let _tasks = tasks;, merely a reference. So by doing that you're mutating the state variable directly. You could remove an element at a given position by simply doing this:

  function deleteTask(pos) {
    setTasks(oldArray => oldArray.filter((item, index) => index !== pos));
  }

This assumes that pos is an integer representing the index of the element you want to remove

Upvotes: 2

Related Questions