Home > Mobile >  removing object from array of objects - react
removing object from array of objects - react

Time:09-29

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>

CodePudding user response:

It deletes it but react does not re-render. You have to use a setState method to trigger the re-render, you could put a copy of DATA in a state variable.

CodePudding user response:

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 = () => {
  const [data, setData] = React.useState([
    {
      id: 1,
      name: "item1"
    },
    {
      id: 2,
      name: "item2"
    }
  ]);

  const deleteItem = (id) => {
   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>

  • Related