I need to fetch data from API based on key and place the data inside a tablecell. I have tried something like the following but didn't work. It is showing an uncaught error.In that case, I know hooks shouldn't be called inside loops, conditions, or nested functions. Then how I would get the item.id
?
Uncaught Error: Rendered more hooks than during the previous render.
My code is:
import React, { useState, useEffect } from 'react';
import {
Table, TableRow, TableCell, TableHead, TableBody,
} from '@mui/material';
import makeStyles from '@mui/styles/makeStyles';
import { useEffectAsync } from '../reactHelper';
import { useTranslation } from '../common/components/LocalizationProvider';
import PageLayout from '../common/components/PageLayout';
import SettingsMenu from './components/SettingsMenu';
import CollectionFab from './components/CollectionFab';
import CollectionActions from './components/CollectionActions';
import TableShimmer from '../common/components/TableShimmer';
const useStyles = makeStyles((theme) => ({
columnAction: {
width: '1%',
paddingRight: theme.spacing(1),
},
}));
const StoppagesPage = () => {
const classes = useStyles();
const t = useTranslation();
const [timestamp, setTimestamp] = useState(Date.now());
const [items, setItems] = useState([]);
const [geofences, setGeofences] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
fetch('/api/geofences')
.then((response) => response.json())
.then((data) => setGeofences(data))
.catch((error) => {
throw error;
});
}, []);
useEffectAsync(async () => {
setLoading(true);
try {
const response = await fetch('/api/stoppages');
if (response.ok) {
setItems(await response.json());
} else {
throw Error(await response.text());
}
} finally {
setLoading(false);
}
}, [timestamp]);
return (
<PageLayout menu={<SettingsMenu />} breadcrumbs={['settingsTitle', 'settingsStoppages']}>
<Table>
<TableHead>
<TableRow>
<TableCell>{t('settingsStoppage')}</TableCell>
<TableCell>{t('settingsCoordinates')}</TableCell>
<TableCell>{t('sharedRoutes')}</TableCell>
<TableCell className={classes.columnAction} />
</TableRow>
</TableHead>
<TableBody>
{!loading ? items.map((item) => (
<TableRow key={item.id}>
<TableCell>{item.name}</TableCell>
<TableCell>{`Latitude: ${item.latitude}, Longitude: ${item.longitude}`}</TableCell>
<TableCell>
{
geofences.map((geofence) => geofence.name).join(', ')
}
</TableCell>
<TableCell className={classes.columnAction} padding="none">
<CollectionActions itemId={item.id} editPath="/settings/stoppage" endpoint="stoppages" setTimestamp={setTimestamp} />
</TableCell>
</TableRow>
)) : (<TableShimmer columns={2} endAction />)}
</TableBody>
</Table>
<CollectionFab editPath="/settings/stoppage" />
</PageLayout>
);
};
export default StoppagesPage;