I currently have the following code:
Users.js
import React, { useEffect, useState } from "react";
import { Box } from "@mui/system";
import {
TableContainer,
Table,
TableHead,
TableRow,
TableCell,
} from "@mui/material";
import { USERS_URL } from "../utils/Constants";
function Users() {
const [users, setUsers] = useState([]);
const [isDone, setIsDone] = useState(false);
useEffect(() => {
fetch(USERS_URL, {
method: "GET",
headers: {"Authorization": sessionStorage.getItem("accessToken")}
})
.then((response) => response.json())
.then((responseData) => {
setUsers({responseData});
})
.catch((error) => console.error(error))
console.log(users);
}, [users]);
return(
<Box sx={{ flexGrow: 1 }}>
<TableContainer>
<Table sx={{ minWidth: 650, maxWidth: 1024 }}>
<TableHead>
<TableRow>
<TableCell>Username</TableCell>
<TableCell align="right">First Name</TableCell>
<TableCell align="right">Last Name</TableCell>
</TableRow>
</TableHead>
</Table>
</TableContainer>
</Box>
);
}
export default Users;
However, as the title states, this endlessly loops when re-rendering the components. How do I stop this from happening once it has called for the list of users I have?
Just for reference, I’m receiving the correct data from my server application as I would expect.
EDIT:-
I’ve changed the code to reflect what was suggested:
useEffect(() => {
...
}, []);
However, the array is now returning empty.
>Solution :
try to replace useEffect(() => {}, [users]); on:
useEffect(() => {
...
}, []);