Home > OS >  React Firebase getDocs & useEffect makes two calls
React Firebase getDocs & useEffect makes two calls

Time:12-29

I'm trying to get data from firebase in react, using useEffect to avoid creating loops.

My code works so far, but I get the results twice. When I tried to find out what the problem was, I found that the data was also retrieved twice. Because the whole code section is executed twice.

--> i get the "Did request!" from console.log("Did request!") 2x times

import React, { useEffect, useState } from "react";
import { db } from "../firebase-config";
import { collection, getDocs } from "firebase/firestore";

function MusicList() {
  const [musicList, setMusicList] = useState([]);

  const getData = async () => {
    try {
      const querySnapshot = await getDocs(collection(db, "music"));
      querySnapshot.forEach((doc) => {
        setMusicList((oldArray) => [...oldArray, doc.data()]);
      });
      console.log("Did request!");
    } catch (error) {
      console.log(error);
    }
  };

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

  return (
    <div className="MusicList">
      {musicList.map((music) => {
        return <div key={music.id}>{music.songName}</div>;
      })}
    </div>
  );
}

export default MusicList;

Being relatively new to React and the concept of "useEffect" I don't know exactly why this is happening.

CodePudding user response:

This is most likely because you have React strict mode enabled? It does this very annoying thing where it renders components twice. Remove it and it should only render once. Let me know if it works:

<StrictMode> <<--- remove this
  <App />
</StrictMode> <<--- remove this

Further information: https://github.com/facebook/react/issues/24502#issuecomment-1118754581

  • Related