Nishant Rai
Nishant Rai

Reputation: 15

list is getting updated but data is updated on dom in reactjs?

Here is my code to create a TODO list, the problem is when I add an item the list is getting updated but when I am deleting an item the list is not getting updated.

import React, { useEffect, useState } from 'react';
import './App.css';

function App(){

  const [item, setItem] = useState("");
  const [list, updateList] = useState([]);

  let todoList = <p>list is empty</p>
  //creating a list
  if(list.length!== 0){
    todoList =  list.map((res, index) =>{
    return <li key={index} onClick={() => deleteItem(index)}>{res}</li>;
    });
  }
  else{

    // adding an item in todo list

    todoList = <p>list is empty</p>
  }

 
  function incre(){
    let addItem = [];
    if(list){
      addItem = list;
      addItem.push(item);
    }
    else{
      addItem = item;
    }
    updateList(addItem);
    setItem("");
  }
  // deleting item from todo list
  function deleteItem(item){
    let updatedList = list;

    updatedList.splice(item, 1);
    console.log(list);
    updateList(updatedList);
  }
  // input query
  let query = (event) =>{
    const { value } = event.target;
    setItem(value);
  }

  return (
    <div className="App">
      <input 
        onChange={(e) => {query(e)}}
        value={item} />
      <button onClick={incre}>
        click me
      </button>
      <p>{item}</p>
      <ul>
        {todoList}
      </ul>
    </div>
  );
}

export default App;

Upvotes: 1

Views: 31

Answers (1)

devserkan
devserkan

Reputation: 17608

Right now you are mutating your state. Creating a new variable and setting to your state does not create a fresh new variable. If you mutate it, you also mutate the original one. So, you should avoid doing this.

Also, push and splice methods mutate the original array. Again, you should avoid doing those methods. Instead, you can use other methods that do not mutate the original arrays.

To add you can use spread syntax:

function incre(){
  updateList(prev => [...prev, item]);
  setItem("");
}

To remove, you can use filter:

function deleteItem(itemIndex){
  const updatedList = list.filter((_, index) => itemIndex !== index)
  updateList(updatedList);
}

Upvotes: 1

Related Questions