简体   繁体   中英

React Firebase getDocs & useEffect makes two calls

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM