Skip to content
Advertisement

removing object from array of objects – react

Why this does not remove item from the list but only for console.log? As you can see i update list in the function that i assign later to the button.

let DATA = [
  {
    id: 1,
    name: "item1"
  },
  {
    id: 2,
    name: "item2"
  }
];

const App = () => {
const deleteItem = (id) => {
    DATA = DATA.filter((item) => item.id !== id);
    console.log(DATA);
  };

  return (
    <div className="App">
      {DATA.map((item) => (
        <p key={item.id} onClick={() => deleteItem(item.id)}>
          {item.name}
        </p>
      ))}
    </div>
  );
}

const root = ReactDOM.createRoot(
  document.getElementById("root")
).render(<App/>);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Advertisement

Answer

It does remove the item from the list. But there’s nothing telling the component to re-render the UI.

What you’re looking for is state in React. Updating state triggers a component re-render:

const App = () => {
  // store the data in state
  const [data, setData] = React.useState([
    {
      id: 1,
      name: "item1"
    },
    {
      id: 2,
      name: "item2"
    }
  ]);

  const deleteItem = (id) => {
    // update state with the new data
    setData(data.filter((item) => item.id !== id));
  };

  return (
    <div className="App">
      {data.map((item) => (
        <p key={item.id} onClick={() => deleteItem(item.id)}>
          {item.name}
        </p>
      ))}
    </div>
  );
}

const root = ReactDOM.createRoot(
  document.getElementById("root")
).render(<App/>);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement