Hi i'm facing a problem with the useEffect hook in React. The code below works like it should but es-lint suggests that i need to provide dependencies in the dependency array from the useEffect.
Working code with // eslint-disable-next-line react-hooks/exhaustive-deps
export default function UsersList() {
const [users, setUsers] = useState<User[]>([]);
const { setError } = useContext(errorContext);
const { isLoading, setIsLoading } = useContext(globalContext);
useEffect(() => {
if (users.length < 1) {
fetchUsers();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
async function fetchUsers () {
try {
setIsLoading(true);
const fetchedUsers = await api.getUsers();
setUsers(fetchedUsers);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
}
}
Infinite looping code
i tried to write it like this the code triggers a infinite loop.. (because the states get constantly changed inside the function and triggers the useEffect every time because of the declared dependencies)
useEffect(() => {
async function fetchUsers () {
try {
setIsLoading(true);
const fetchedUsers = await api.getUsers();
setUsers(fetchedUsers);
} catch (error) {
setError(error);
} finally {
setIsLoading(false);
}
}
if (users.length < 1) {
fetchUsers();
}
}, [setIsLoading, setError, users]);
i also tried putting the fetchUsers() inside the dependencies array but this had no effect.
How do i properly set up a async call when the component mounts without having to use // eslint-disable-next-line react-hooks/exhaustive-deps ?