I receive a JSON from an API call that looks like this
[
{
"time1": "17:30",
"time2": "19:30",
"day": "Sunday",
"trainingsid": 1
},
{
"time1": "15:30",
"time1": "18:30",
"day": "Monday",
"trainingsid": 2
},
]
As soon as I click the Delete button, the element should be removed from the database and additionally it should be removed from the array trainingsData.
The problem is that I remove the element with e.g. the ID 1 from the trainingsData, which also works, I then receive the following JSON object back
[
{
"time1": "17:30",
"time2": "19:30",
"day": "Sunday",
"trainingsid": 1
},
null
]
My problem now is that the correct data does not appear in the setTrainingsData. This means that both dates are still displayed, although only one time is still available. My question now is, if I can remove the one element from the trainingsData and so that it is also updated?
import React, { useState, useEffect } from 'react'
function Training({}) {
const [trainingData, setTrainingData] = useState([]);
.
.
.
const deleteData = (id) => {
//setTrainingData([]);
var json = trainingData;
console.log(json)
var key = 2;
delete json[key]
console.log(json)
setTrainingData(json)
}
return (
<div>
{trainingData.map((d, i) => (
<div
key={i}
>
{d.day} - {d.time1} bis {d.time2} Uhr
<button className="button is-danger" onClick={() => deleteTraining(d.trainingsid)}>Delete</button>
<br />
</div>
))}
</div>
)
}
export default Training