M R
M R

Reputation: 17

React Hooks infinite loop Memory leak?

Hello i have a problem with infinite loops. All the exampels i look at makes the loop go away. But then it wont update my view if i dont refresh. I want the items to appear when something gets added. i thought my example would work but it does not. I dont know how to fix it

      const [ReadBookingTimes, SetBookingTimes] = useState([]);
      const [readStatus, setStatus] = useState("");
        
        const getBookingTimes = async () => {
            try {
              const response = await Axios.get(`${API_ENDPOINT}`);
              console.log(response);
              // debugger;
              SetBookingTimes(response.data);
              // setStatus("Connection sucsessfull");
            } catch (err) {
              setStatus("Error getting BookingTimes");
            }
          };
        
          //reupdate State and prevent infinite loop
          useEffect(() => {
            getBookingTimes(ReadBookingTimes);
          }, [ReadBookingTimes]); //);

Upvotes: 1

Views: 347

Answers (1)

Navid Zarepak
Navid Zarepak

Reputation: 4208

Your useEffect has a dependancy ReadBookingTimes which updates every time. Bascially, you update the ReadBookingTimes every single time over and over again.

What you should do is to add a condition to check if your data is already loaded and if so, don't call the function:

const [ReadBookingTimes, SetBookingTimes] = useState([]);
const [readStatus, setStatus] = useState("");

const [dataLoaded, setDataLoaded] = useState(false);


 const getBookingTimes = async () => {
     // Your fetch code
     setDataLoaded(true)
 }

 useEffect(() => {
     // don't go any further of data is already loaded.
     if (dataLoaded) return;

     getBookingTimes(ReadBookingTimes);
 }, [ReadBookingTimes, dataLoaded]);

Now you won't get stuck in a loop. And anytime you want to reload the data, you can change the dataLoaded to false and useEffect will call the getBookingTimes function again.

In case you want to get the data every 2 minutes for example, you can add a timeout to change the dataLoaded state every time causing another data reload.

Upvotes: 1

Related Questions