I am a new beginner in JS. Essentially the gist of the issue is this:
I have a MySQL database from where I am loading my table data through Axios
There are CRUD operations in my web app, which updates my DB anytime a request is made
All the functions work and the changes get reflected in the backend, but not on the Datagrid unless I do a hard window reload
I want to have a refresh button, which when clicked gets the new data from my database with no hard reload
I know it might be possible through a combination of setState variables and useEffect but all my attempts throughout the weekend have failed so far. Any idea how to integrate them together?
data.js
import axios from "axios";
export const getData = async () => {
let response = await axios.get('http://localhost:8080/h2h-backend/list');
console.log(response.data);
return response.data;
}
Datagrid
import { getData } from '../services/data';
export default function DataTable() {
const [pageSize, setPageSize] = React.useState(10);
const [data, setData] = React.useState([]);
useEffect(async () => {
setData(await getData());
}, [])
let rows = searchInput
? data.filter((item) => item.cust_number.toString().match(new RegExp("^" +
searchInput, "gi")))
: data;
return (
<div style={{ width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
autoHeight={true}
density='compact'
rowHeight={40}
/>
)
refreshbutton.js
export default function RefreshButton() {
return (
<Grid item xs={0.5} backgroundColor="rgba(39,61,74,255)" >
<IconButton
aria-label="refresh"
size="small"
sx={iconSx}
onClick={() => {
window.location.reload();
}}
>
<RefreshIcon sx={{fontSize: "18px"}}/>
</IconButton>
</Grid>
);
}
The problem is on how you are using the useEffect method in your DataTable component.
This is a NO NO
useEffect(async () => {
setData(await getData());
}, [])
Why?
useEffectis supposed to be a function that returns either nothing or a function. But an async function returns a Promise, which can't be called as a function! It's simply not what the useEffect hook expects for its first argument.
This should work
useEffect(() => {
getData()
}, [])
With axios you have the alternative of doing a synchronous function without the async/await. Like so:
import axios from "axios"
export function getData(){
let url = 'http://localhost:8080/h2h-backend/list'
let dataFetched = undefined
axios.get(url)
.then((resp) => dataFetched = resp.data)
.catch((error) => console.log(error))
return dataFetched
}