Reputation: 344
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.
Upvotes: 0
Views: 64
Reputation: 4474
You should remove users
from the dependency array. This is because when the effect runs, you'll set the users
state. And since you set the state, the component rerenders, and react checks if any effects need to run. Since users
has changed, react will run the effect again, setting the state again, and so on.
Upvotes: 2
Reputation: 43
try to replace useEffect(() => {}, [users]); on:
useEffect(() => {
...
}, []);
Upvotes: -1