J
J
JekaHC2022-04-17 18:47:53
React
JekaHC, 2022-04-17 18:47:53

Why is a function inside a component called an infinite number of times?

I have a component:

import { Hotels } from "./Hotels";
import WelcomePage from "./WelcomePage";

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
import {
  getFirestore,
  collection,
  getDocs,
  addDoc,
} from "https://www.gstatic.com/firebasejs/9.6.0/firebase-firestore.js";
import {
  getAuth,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  onAuthStateChanged,
  signOut,
} from "https://www.gstatic.com/firebasejs/9.6.0/firebase-auth.js";

import { firebaseConfig, app, db, auth } from "../firebaseConfig";

import { useState } from "react";

function MainPage() {
  const [hotels, setHotels] = useState([]);
  const [authentication, setAuthentication] = useState(false);

  async function fetchHotels() {
    const _hotels = [];
    const querySnapshot = await getDocs(collection(db, "reviews"));
    querySnapshot.forEach((doc) => {
      _hotels.push(doc.data());
    });
    console.log("fetched!");
    setHotels(_hotels);
  }
  function isAuthenticated() {
    onAuthStateChanged(auth, (user) => {
      if (user) {
        // User is signed in, see docs for a list of available properties
        const uid = user.uid;
        setAuthentication(true);
      } else {
        // User is signed out
        setAuthentication(false);
      }
    });
  }
  isAuthenticated();
  fetchHotels();

  return (
    <main className="content">
      <Hotels hotels={hotels} />
    </main>
  );
}

export default MainPage;

After the application starts, the fetchHotels function begins to be called endlessly (this is evidenced by ). Under the same conditions, other functions are adequately called in other components. console.log("fetched!")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GlazOtca, 2022-04-17
@GlazOtca

Inside the fetchHotels() function, you call the state setting - setHotels(_hotels); Setting the state obliges React to do a re-render. The rerender calls the fetchHotels() function again and the circle repeats. What's strange? As written, it works.
To work correctly, side effects need to be called inside the useEffect hook and the dependencies must be set correctly for it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question