Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React UseEffect endless loop despite trying to add dependencies

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(() => {
   ...
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading