I am stuck on a problem. I have data object on server db.json running on port 3001/person and I have designed delete button which should delete specific object when clicked. But when I click delete, it deletes from db.json server but UI part doesn’t update until and unless I refresh the page. I want help in this
App.js
import { useState,useEffect } from 'react';
import personService from './services/person'
function App() {
const [persons, setPersons] = useState([
// { name: 'Arto Hellas', number: '00000000', id: 1 },
]);
const [newName, setNewName] = useState('');
const [newNum, setNewNum] = useState('');
const [searchTerm, setSearchTerm] = useState('');
const handleNameInput = (e) => {
setNewName(e.target.value);
};
const handleNumberInput = (e) => {
setNewNum(e.target.value);
};
const handleSearchTerm = (e) => {
setSearchTerm(e.target.value);
};
const addName = (e) => {
e.preventDefault();
if (persons.some((person) => person.name === newName)) {
alert(`${newName} already exists`);
return;
}
const nameObject = {
name: newName,
number: newNum,
id: persons.length + 1,
};
personService.create(nameObject).then(response=>{
setPersons(persons.concat(response.data));
setNewName('');
setNewNum('');
})
};
useEffect(()=>{
personService.getAll().then(response=>{
setPersons(response.data)
})
},[])
const filteredPersons = persons.filter((person) =>
person.name.toLowerCase().includes(searchTerm.toLowerCase())
);
const deletePerson=(id)=>{
const personn={...persons}
personService.deletee(id,personn).then(response=>{
console.log('deleted',id)
}).catch((err)=>{
alert("ERROR",err)
})
}
return (
<div>
<h1>PHONEBOOK</h1>
<div>
Filter shown with: <input onChange={handleSearchTerm} value={searchTerm} />
</div>
<form>
<div>
<h2>ADD</h2>
<div>
name: <input onChange={handleNameInput} value={newName} />
</div>
<div>
number: <input onChange={handleNumberInput} value={newNum} />
</div>
</div>
<button type="submit" onClick={addName}>
add
</button>
</form>
<h2>Numbers</h2>
<ul>
{filteredPersons.map((person) => (
<li key={person.id}>
{person.name} {person.number} <button onClick={()=>deletePerson(person.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
}
export default App;
I am expecting to get help how to update the UI part also when Delete button is clicked
2
Answers
You need to re-fetch your data again:
When you delete an item using the delete API, it only updates the server’s database. To reflect this change in the UI, you need to make an additional GET request to fetch the updated data from the server and then update the state in your React application. This ensures that the UI stays synchronized with the server data without requiring a full page refresh.