0

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>

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.