0

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.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Codesk
  • 25
  • 4

1 Answers1

0

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

UPDATE: I should mention this is a quick fix. The double rendering is done to ensure you've put in features such as query caching etc where bugs can be detected by double rendering.

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

Sam
  • 24
  • 1
  • 4
  • 1
    Removing `SrictMode` is a bad idea. To handle it well see https://stackoverflow.com/questions/72238175/why-useeffect-running-twice-and-how-to-handle-it-well-in-react – Youssouf Oumar Dec 31 '22 at 17:26