1차시도
useEffect(() => {
const q = query(
collection(dbService, "recipe"),
orderBy("createdAt", "desc")
);
const getList = onSnapshot(q, (snapshot) => {
const newItems = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
console.log(newItems);
setCurrentItems(newItems);
});
getList();
}, []);
콘솔에 q는 잘 나왔지만 그 다음 함수인 newItems가 찍히지 않았다. 리액트네이티브때 썼던 코드인데 그때는 맞고 지금은 틀린 이유가 뭐야 대체
2차 시도
useEffect(() => {
const getList = async () => {
const items = query(
collection(dbService, "recipe"),
orderBy("createdAt", "desc")
);
const querySnapshot = await getDocs(items);
querySnapshot.forEach((doc) => {
const newObj = {
...doc.data(),
id: doc.id,
};
console.log(doc.data());
setCurrentItems((prev) => [...prev, newObj]);
});
};
getList();
}, []);
새로고침할때마다 같은 데이터가 반복해서 추가..
완성코드
const [currentItems, setCurrentItems] = useState<RecipeProps[]>([]);
const getList = async () => {
const items = query(
collection(dbService, "recipe"),
orderBy("createdAt", "desc")
);
const querySnapshot = await getDocs(items);
const newData = querySnapshot.docs.map((doc) => ({
...doc.data(),
id: doc.id,
}));
setCurrentItems(newData);
};
useEffect(() => {
getList();
}, []);
return안써서 화면에 왜 안나오지 하고 2시간 고민했다