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.