React useEffect infinite loop fetching data from an api

Ryan Tillaman :

Hi I'm trying to make a twitter clone app. I am using React on the client side and Express on the server side and PostgreSQL as my database. So here's the problem, I'm trying to use the useEffect like this:

const [tweets, setTweets] = useState([]);
  const getTweets = async () => {
    const res = await api.get("/posts", {
      headers: { token: localStorage.token },
    });
    setTweets(res.data);
  };
  useEffect(() => {
    getTweets();
  }, [tweets]);

I have no idea why it's looping infinite times, am I using it correctly though? I want the tweets to be updated every time I post a tweet. It's working fine but it's running infinite times. I just want it to re-render if a tweet got posted.

Here's my server code for getting all the posts:

async all(request: Request, response: Response, next: NextFunction) {
    return this.postRepository.find({
      relations: ["user"],
      order: {
        createdAt: "DESC",
      },
    });
  }
alikondie :

The problem is every time you change the tweets it executes useEffect and changes the tweets and so long and so forth, so it's natural that it loops infinitely, the solution is to add a trigger that you set to true when a tweet gets posted, so the solution would be like this

const [tweets, setTweets] = useState([]);
const [isFetching, setIsFetching] = useState(false);
  const getTweets = async () => {
    const res = await api.get("/posts", {
      headers: { token: localStorage.token },
    });
    setTweets(res.data);
  };

  useEffect(() => {
    getTweets();
    setIsFetching(false);
  }, [isFetching]);

and set some logic to use setIsFetching(true) in order to execute the useEffect

PS: if you use an empty array in useEffect, it would execute only when the component is mounted (at the start)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related