Reputation:
I am writing my react as a function component. I want to execute fetch and wait for it finished before rendering. but fetch always sends a pending promise and records is null when it renders. How do I make it a synchronous process?
export default function SimpleTable() {
const classes = useStyles();
let records = null;
fetch(socket+'get_all_records')
.then(response => response.json())
.then(json => {records = json.record});
return (
<Paper className={classes.root}>
<Table className={classes.table} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell align="right">DoorId</TableCell>
<TableCell align="right">Time</TableCell>
<TableCell align="right">Permission</TableCell>
<TableCell align="right">Image</TableCell>
</TableRow>
</TableHead>
<TableBody>
{records.map(record => (
<TableRow key={record.UserID}>
<TableCell component="th" scope="row">{record.UserID}</TableCell>
<TableCell align="right">{record.DoorID}</TableCell>
<TableCell align="right">{record.Time}</TableCell>
<TableCell align="right">{record.AccessGranted}</TableCell>
{/*<TableCell align="right">{record.ImageID}</TableCell>*/}
<TableCell>
<img src={socket+'get_image?image_id='+record.ImageID} height="42" width="42"/>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
);
}
Upvotes: 1
Views: 377
Reputation: 5657
First of all, records
needs to be a state, otherwise reassigning it (then(json => {records = json.record})
) won't trigger a re-render.
And you can use conditional rendering to decide what your component renders depending on the value of records
:
export default function SimpleTable() {
const [records,setRecords] = useState(null);
useEffect(() => {
fetch(socket+'get_all_records')
.then(response => response.json())
.then(response => {setRecords(response)});
}, []);
return (
!response ? <Loading /> : (
<Paper className={classes.root}>...</Paper>
)
)
}
Upvotes: 1