Search code examples
reactjsfunctionstatecall

Why every element I create gets deleted istantly?


I am making a Contact Manager(I already did it with App as a class component and now I am doing it with App as a functional component) and every time I create an element, it gets deleted instantly because the removeElement function is called instantly...Can someone tell me why?

P.S. Sorry for my terrible English...

this is the link of the code

import "./styles.css";
import React from "react";

export default function App() {
  const [people, setPeople] = React.useState([]);
  const [person, setPerson] = React.useState({
    name: "",
    age: "",
    email: ""
  });

  const handleChange = (e) => {
    setPerson({ ...person, [e.target.name]: e.target.value });
  };

  const handleSubmit = () => {
    if (person.name && person.age && person.email) {
      const newPerson = { ...person, id: new Date().getTime().toString() };
      setPeople([...people, newPerson]);
      setPerson({ name: "", age: "", email: "" });
    }
  };

  const removeItem = (id) => {
    setPeople(people.filter((person) => person.id !== id));
  };

  const clearList = () => {
    setPeople([]);
  };

  return (
    <div className="container">
      <h1>React Contact Manager</h1>

      <div className="inputs">
        <input
          type="text"
          name="name"
          value={person.name}
          onChange={handleChange}
        />

        <input
          type="number"
          name="age"
          value={person.age}
          onChange={handleChange}
        />

        <input
          type="mail"
          name="email"
          value={person.email}
          onChange={handleChange}
        />
      </div>

      <button onClick={handleSubmit}>Add</button>

      <ul className="result">
        {people.map((person) => (
          <li key={person.id}>
            <h4>{person.name}</h4>
            <h6>{person.age}</h6>
            <span>{person.email}</span>
            <button onClick={removeItem(person.id)}>Remove</button>
          </li>
        ))}
      </ul>

      <div className="clear">
        <button onClick={clearList}>Clear</button>
      </div>
    </div>
  );
}


Solution

  • Item is deleted because you are executing this function - removeItem(person.id) - on every render.

    Change:

    <button onClick={removeItem(person.id)}>Remove</button>
    

    to:

    <button onClick={() => removeItem(person.id)}>Remove</button>
    

    Or create a function and assign it to the button:

    const removePerson = () => {
       removeItem(person.id);
    }
    <button onClick={removePerson}>Remove</button>