I want to implement a "delete contact when clicked" in a simple contact manager app I'm making to learn React but it is very buggy. The first time I click the item to delete it does nothing and when clicked another time it deletes the previous one. I'm new learning react and don't know why is this happening, someone can help?
const { useState } = React;
function AddPersonForm(props) {
const [person, setPerson] = useState("");
function handleChange(e) {
setPerson(e.target.value);
}
function handleSubmit(e) {
props.handleSubmit(person);
setPerson("");
e.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Add new contact"
onChange={handleChange}
value={person}
/>
<button type="submit">Add</button>
</form>
);
}
function PeopleList(props) {
const [person_, setPerson_] = useState("");
function handleCLick(e) {
setPerson_(e.target.textContent);
props.handleCLick(person_);
}
return (
<ul onClick={handleCLick}>
{props.data.map((val, index) => (
<li key={index}>{val}</li>
))}
</ul>
);
}
function ContactManager(props) {
const [contacts, setContacts] = useState(props.data);
function addPerson(name) {
setContacts([...contacts, name]);
}
function removePerson(name_) {
let filtered = contacts.filter(function (value) {
return value != name_;
});
setContacts(filtered);
}
return (
<div>
<AddPersonForm handleSubmit={addPerson} />
<PeopleList data={contacts} handleCLick={removePerson} />
</div>
);
}
const contacts = ["James Smith", "Thomas Anderson", "Bruce Wayne"];
ReactDOM.render(
<ContactManager data={contacts} />,
document.getElementById("root")
);
Having the onClick handler on the unordered list element seems a bit odd to me, but your issue a misunderstanding of when React state updates. React state updates are enqueued and asynchronously processed. In other words, when you enqueue the state update setPerson_(e.target.textContent) in handleClick in PeopleList, that person_ hasn't updated on the next line props.handleCLick(person_);. You are using state that hasn't updated yet.
Just send the click event object's value to the props.handleClick callback directly. You can also remove the local person_ state.
function PeopleList(props) {
function handleCLick(e) {
props.handleCLick(e.target.textContent);
}
return (
<ul onClick={handleCLick}>
{props.data.map((val, index) => (
<li key={index}>{val}</li>
))}
</ul>
);
}