On my table when a value is input, it is stored to localstorage as a 2D array and mapped to a table on a new seperate row. When a new row is created, it also has its own delete button. When that delete button is clicked, that specific row with the button will be deleted.
an example is [['hello', 'hi', 'hey'], ['bye', 'goodbye', 'cya']]
; the first nested array would have the 3 data it contains mapped on one row, and the second nested array on the next row. If I wanted to delete the first row, I would click the delete button which would result in the first nested array being removed resulting in the first row being removed.
Since the table is based off of localstorage, I will need to delete that specific array but keep the others. I think I can achieve this by getting that nested arrays index and removing it. Now I am not sure whether I need to use .splice()
or another method?. This is the method I have used which has not worked:
const getData = [JSON.parse(localStorage.getItem('pls'))];
const tableDatas = [...getData];
const handleSingleDelete = (index) => {
//what do I place here? I tried this:
getItem.splice(index, 1)
}
...
return(
<Table className="tablesorter" responsive id="maintb">
<tbody id="tbid">
{(tableDatas.map((l,i) => (
<tr key={`${l+i}`} id={`${i}`}>
<td>{tableDatas[i][1]}</td>
<td>{tableDatas[i][2]}</td>
<td>{tableDatas[i][3]}</td>
<td>
<Button onClick={handleSingleDelete}>Delete
</Button>
</td>
</tr>
</tbody>
<Table>
)
You should get the Array from the localStorage
each time you want to make a change in it, because you always need the most recent data, calling it first will always have the same array and any future changes to the localstorage will not be updated in the variable until you call it again.
First bring it into the function, then remove the index you want and parse again to save it to the localstorage
:
EDIT:
In order to render the data, useState
can be used, and updating it each delete.
const localStorageName = "pls";
const [arrData, setArrData] = useState(JSON.parse(localStorage.getItem(localStorageName)))
const handleSingleDelete = (index) => {
const currentArray = JSON.parse(localStorage.getItem(localStorageName));
currentArray.splice(index, 1);
localStorage.setItem(localStorageName, JSON.stringify(currentArray))
setArrData(() => currentArray)
}
Now use this arrData
to loop in the component and render always the most up-to-date data.