Reputation: 1
I am facing one problem while using material ui.
const [selectedRows, setSelectedRows] = useState([]);
useEffect(() => {
localStorage.setItem('row_selected', JSON.stringify(selectedRows));
}, [selectedRows]);
// return
<DataGrid
components={{
NoRowsOverlay: NoRows,
Toolbar: GridToolbar,
}}
rows={tableData}
columns={columns}
checkboxSelection
selectionModel={JSON.parse(localStorage.getItem('row_selected'))}
onSelectionModelChange={setSelectedRows}
hideFooterPagination
/>
I'm using the checkbox function of datagrid, and even if I refresh the page, I'm saving it in local storage to maintain the checked.
However, the problem is that local storage is also reset because the new value is reset every refresh.
How can I keep it refreshed?
I saw this example enter link description here, but I think it's different from the new value problem that automatically reset every refresh.
Upvotes: 0
Views: 929
Reputation: 109
You can use this code I've created ... I tested it and it works good
import * as React from "react";
import { DataGridPro } from "@mui/x-data-grid-pro";
export default function DataGridProDemo() {
const [selectionModelItems, setSelectionModel] = React.useState([]);
React.useEffect(() => {
const parsedArrayFromLocalStorage = JSON.parse(localStorage?.getItem("SelectedOption") || "[]");
const mappedArray = parsedArrayFromLocalStorage.map(item => {
return item;
}, [selectionModelItems]);
console.log("log", mappedArray);
setSelectionModel(mappedArray);
}, []);
console.log("selectionModelItems from outsource is : ", selectionModelItems);
return (
<div style={{ height: 520, width: "100%" }}>
<DataGridPro
columns={[
{ field: 'default', width: 150 },
{ field: 'name', width: 150 },
{ field: 'stars', width: 150 },
]}
rows={[
{
id: 1,
name: 'MUI',
stars: 28000,
default: 'Open source',
},
{
id: 2,
name: 'DataGridPro',
stars: 15000,
default: 'Enterprise',
},
]}
rowHeight={38}
checkboxSelection
disableSelectionOnClick
onSelectionModelChange={(ids) => {
// ids is array of seleced rows
console.log("ids is : ", ids);
setSelectionModel(ids);
// i made this condtion because onSelectionModelChange called after each render of the component and without this conditon storage will be empty every refresh
if (ids.length > 0) {
localStorage.setItem("SelectedOption", JSON.stringify(ids));
}
}}
selectionModel={selectionModelItems ? selectionModelItems : []}
/>
</div>
);
}
Upvotes: 1