1

Having a weird issue where by i am fetching some data from my local api, and it is infinately calling it for some strange reason:

import React, { useState, useEffect } from 'react';

const Users = () => {
    const [users, setUsers] = useState([])

    const fetchUsers = async () => {
        try {
            await fetch('http://localhost:3001/users')
            .then(response => response.json())
            .then(data => setUsers(data));
        }
        catch(ex) {
            console.error('ex:', ex);
        }
    }
    useEffect(() => {
        fetchUsers();
    }, [users])

   return <div>xxx</div>
}

export default Users;

If I console.log(data) instead of setUsers(data), then all seems to be fine and the console log only outputs 1 set of information.

I am unsure what I am doing wrong. Any ideas?

1
  • 1
    Remove users as a dependency of useEffect. You don't need it, and this causes the infinite loop. Commented Apr 2, 2021 at 20:26

2 Answers 2

3
useEffect(() => {
    fetchUsers();
}, [users])

should be:

useEffect(() => {
    fetchUsers();
}, [])

The first will fetch users every time user changes. then it changes the users object with the results which causes the infinite loop.

The fix instead only calls it once on mount.

Sign up to request clarification or add additional context in comments.

Comments

1

Your effect:

useEffect(() => {
    fetchUsers();
}, [users]);

will be executed whenever someone changes users object. In this case, the first time you will call useEffect, and fetch data from API, when you receive data from the backend you will update users object and trigger an infinite loop.

You can solve problem with:

useEffect(() => { fetchUsers(); }, []);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.