Reputation: 664
What is the most efficient way to update the state here so that deleted records are gone without needing to reload page? Can I do state manipulation inside my deleteTime function? Or is a new function required so that it changes state on button click?
const [time, setTime] = useState([]);
useEffect(() => {
Axios.get('/api/time').then(res => {
const time = res.data;
setTime(time);
})
return () => {
//
};
}, []);
const deleteTime = async (id) => {
await Axios.delete('/api/time/'+id)
}
<button onClick={()=> {console.log(time);deleteTime(time._id);}} className="single">DELETE</button>
Upvotes: 0
Views: 485
Reputation: 164766
You could either delete the specific entry from the time
array (by setting a new state without it) or re-fetch and populate time
from /api/time
. It's up to you which approach you feel works best for your application.
The former would look something like this
const deleteTime = async id => {
await Axios.delete(`/api/time/${encodeURIComponent(id)}`)
setTime(time => time.filter(({ _id }) => _id !== id))
}
The latter, like this
const fetchTime = async () => {
const { data } = await Axios.get("/api/time")
setTime(data)
}
const deleteTime = async id => {
await Axios.delete(`/api/time/${encodeURIComponent(id)}`)
fetchTime()
}
useEffect(() => {
fetchTime()
}, [])
Upvotes: 1