Reputation: 13
Im just trying to remove the list item from the list using onClick with a button. I was following a book called Road to React but it still doesn't update the state of the list(returns new list without the deleted item).It appears to me that im doing something wrong in the removePerson function and using the filter function but I just cant wrap my head around what it is.
import React from 'react';
import { useEffect, useState } from 'react';
const ljudi = [
{
id: '1',
ime: 'Deni',
prezime: 'Ivančok',
dob: 24,
},
{
id: '2',
ime: 'Ana',
prezime: 'Fišer',
dob: 21,
},
{
id: '3',
ime: 'Fran',
prezime: 'Fišer',
dob: 21,
},
];
function App() {
const [people, setPeople] = useState(ljudi);
const removePerson = (personToDelete) => {
const newPeople = people.filter(
(person) => personToDelete !== person
);
setPeople(newPeople);
};
return (
<>
<h1>TIPKE</h1>
<Lista lista={ljudi} removePerson={removePerson} />
</>
);
}
const Lista = ({ lista, removePerson }) =>
lista.map(
(covjek) => <Covjek covjek={covjek} removePerson={removePerson} />
);
const Covjek = ({ covjek, removePerson }) => {
return (
<>
<div id="lista">
<ul key="list">
<li key="1">{covjek.id}</li>
<li key="2">{covjek.ime}</li>
<li key="3">{covjek.prezime}</li>
<li key="4">{covjek.dob}</li>
</ul>
<button id="tipka-liste" onClick={() => removePerson(covjek)}>
Delete
</button>
</div>
</>
);
};
export default App;
Upvotes: 0
Views: 58
Reputation: 693
In JavaScript, you cannot compare objects because they are compared by memory reference and not by value (e.g. object an is not equal to object b even though it has the same properties with identical values).
In this case, you are comparing the whole object, which is wrong, you should compare a string value, for example, the id
property, this is ideal in your case.
I excluded non-needed components to minimize code
import React from 'react';
import { useEffect, useState } from 'react';
function App() {
const [tekst, settekst] = useState('');
const TekstHandler = (event) => {
settekst(event.target.value);
};
const [people, setPeople] = useState(ljudi);
const removePerson = (personId) => {
const newPeople = people.filter(
(person) => personId !== person.id
);
setPeople(newPeople);
};
//lista property has to be `people` and not ljudi
return (
<>
<h1>TIPKE</h1>
<Lista lista={people} removePerson={removePerson} />
</>
);
}
// make sure to include the key property to `Covjek`
const Lista = ({ lista, removePerson }) =>
lista.map(
(covjek, i) => <Covjek key={`${i}`} covjek={covjek} removePerson={removePerson} />
);
const Covjek = ({ covjek, removePerson }) => {
return (
<>
<div id="lista">
<ul>
<li>{covjek.id}</li>
<li>{covjek.ime}</li>
<li>{covjek.prezime}</li>
<li>{covjek.dob}</li>
</ul>
<button onClick={() => removePerson(covjek.id)}\>
Delete
</button>
</div>
</>
);
};
Upvotes: 1