So im fetching data and passing to datagrid as a state but when a page change occurs it isnt updating unless another state change occurs(data is fetched correctly though).So for example i change the page data fetches but datagrid isnt updated,page is changed again now the data fetched previously is shown ,so its like always 1 step behind
const Transaction = () => {
//searchbox input
const search_text = useRef("");
const [rows, setRows] = useState({ rows: [], count: 0 });
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
const [isInvoicePopupOpen, setIsInvoicePopupOpen] = useState(false);
const [options, setOptions] = useState(null);
const [selectedRow, setSelectedRow] = useState({
id: "",
DatePayed: "",
DateIssued: "",
Total: "",
Project: "",
Status: "",
Client: "",
});
//pagination
const [paginationModel, setPaginationModel] = useState({
page: 0,
pageSize: 5,
});
const params = useRef({
limit: paginationModel.pageSize,
page: paginationModel.page + 1,
projectName: search_text ? search_text.current.value : "",
status: options ? options.Status : null,
});
useEffect(() => {
const getOptions = () => {
const storedOptions = localStorage.getItem("transactionFilters");
if (storedOptions) {
setOptions(JSON.parse(storedOptions));
}
};
getOptions();
}, [isDrawerOpen]);
useEffect(() => {
const cleanupLocalStorage = () => {
localStorage.removeItem("transactionFilters");
};
// Cleanup localStorage on page refresh or exit
window.addEventListener("beforeunload", cleanupLocalStorage);
return () => {
window.removeEventListener("beforeunload", cleanupLocalStorage);
};
}, []);
useEffect(() => {
params.current = {
limit: paginationModel.pageSize,
page: paginationModel.page + 1,
projectName: search_text ? search_text.current.value : "",
status: options ? options.Status : null,
};
console.log(params);
}, [paginationModel, options]);
const { data, loading, error } = useFetch(
"transaction",
params.current,
paginationModel
);
useEffect(() => {
if (data) {
setRows(data.data);
}
console.log('changed data')
}, [data]);
//pass it as prop to datagrid
const handlePaginationModelChange = (newModel) => {
setPaginationModel(newModel);
};
// Function when a row is clicked
const handleRowClick = (params, event, details) => {
setSelectedRow(params.row);
};
//close invoice popup
const handleCloseInvoicePopup = () => {
setIsInvoicePopupOpen(false);
};
const handleEnter = (event) => {
if (event.key === "Enter") {
params.current.projectName = search_text.current.value;
setPaginationModel((prevPaginationModel) => ({
...prevPaginationModel,
page: 0,
}));
}
};
const handleSubmit = () => {
setPaginationModel((prevPaginationModel) => ({
...prevPaginationModel,
page: 0,
}));
};
if (loading) {
return (
<Container
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "60vh",
}}
>
<CircularProgress size={200} />
</Container>
);
}
if (error) {
return <div>Error: {error.message}</div>;
}
if (!data) {
return <div>No data available</div>;
}
const columnss = [
...columns,
{
field: "actions",
headerName: "",
headerClassName: "hideRightSeparator",
sortable: false,
width: 400,
renderCell: (params) => (
<ActionColumn
View={() => setIsInvoicePopupOpen(true)}
Edit={() => setIsInvoicePopupOpen(true)}
Delete={() => setIsInvoicePopupOpen(true)}
/>
),
},
];
console.log("reloaded component");
return (
<>
<Stack spacing={2}>
<SearchBox fct={handleEnter} ref={search_text} />
<DataTable
rows={rows.rows}
columns={columnss}
rowCount={rows.count}
filters={filters}
paginationModel={paginationModel}
onPaginationModelChange={handlePaginationModelChange}
onRowClick={handleRowClick}
handleSubmit={handleSubmit}
drawer={() => setIsDrawerOpen(true)}
/>
</Stack>
<InvoicePopup
isOpen={isInvoicePopupOpen}
onClose={handleCloseInvoicePopup}
rowData={selectedRow}
/>
<FilterForm
filterss={filters}
isOpen={isDrawerOpen}
onClose={() => setIsDrawerOpen(false)}
/>
</>
);
};
export default Transaction;
This is the useFetch hook:
import { useState, useEffect } from 'react';
import axios from 'axios';
const useFetch = (url,params,reload) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
console.log(params);
useEffect(() => {
const fetchData = async () => {
try {
const response = await
axios.get("http://localhost:5000/api/"+url,{params});
setData(response.data);
} catch (error) {
setError(error);
console.log(error);
} finally {
setLoading(false);
}
};
fetchData();
console.log('fetched data')
}, [url,reload]);
return { data, loading, error };
};
export default useFetch;