0

I am new in react. I am trying of doing a web request to an endpoint but this response is executing in an infinite loop.

import "./styles.css";
import instance from "./instance";
import { useEffect, useState } from "react";
export default function App() {
const [data, setData] = useState({});

useEffect(() => {
  const getData = async () => {
    try {
      const data = await instance.get("todos/1");
      setData(data.data);
      console.log(data.data);
    } catch (e) {
      console.log(e);
    }
  };
  //getData();
});
 return <div className="App">data:{data?.title}</div>;
}

Why? how can fix it?

enter image description here

This is my live code:

https://codesandbox.io/s/compassionate-almeida-mo2wh?file=/src/App.tsx

yavgz
  • 275
  • 3
  • 17
  • Does this answer your question? [Infinite loop in useEffect](https://stackoverflow.com/questions/53070970/infinite-loop-in-useeffect) – Matt U Dec 02 '21 at 04:42

2 Answers2

2
useEffect(() => {
  const getData = async () => {
    try {
      const data = await instance.get("todos/1");
      setData(data.data);
      console.log(data.data);
    } catch (e) {
      console.log(e);
    }
  };
  //getData();
}, [data]);

You need to provide the variable on which rerender should happen for useEffect, else for every change it will be triggered.

Daniel Paul
  • 495
  • 1
  • 6
  • 13
  • thanks, in my code why a loop is generated? I just have called this function once.. – yavgz Dec 02 '21 at 04:35
  • currently your code not works for me... Nothing happens.. – yavgz Dec 02 '21 at 04:38
  • 2
    @yavgz When you don't supply a second argument, either empty array or which state dependencies trigger a re-render, the `useEffect` hook is invoked when mounted *and* when any state changes. Since you're updating state inside `getData` it causes the component to re-render and so the hook is called again. And you need to uncomment the `getData()` line. – Matt U Dec 02 '21 at 04:40
2

You should add an empty array as dependency in useEffect so that the useEffect runs only once and data is fetched only once.

   useEffect(() => {
     const getData = async () => {
     try {
     const data = await instance.get("todos/1");
     setData(data.data);
     console.log(data.data);
    } catch (e) {
     console.log(e);
    }
   };
   getData();
   },[]);
  • thanks, in my code why a loop is generated? I just have called this function once.. – yavgz Dec 02 '21 at 04:40
  • The useEffect hook gets executed in every render if the empty array is not set as dependeny. If you set an empty array as dependency in useEffect then it will only execute once. Since you are using `setData` inside `getData` function this will trigger the component to re-render which will execute the useEffect. – Pariskrit Moktan Dec 02 '21 at 04:45