{ snapshot.forEach((doc) => { const newProduct = { id: doc.id, ...doc.data(), }; if (index === 0) { products.push(newProduct); } else { savingbaseList.push(newProduct); } }); }); optionListSnapshots.forEach((snapshot, index) => { snapshot.forEach((doc) => { const newProduct = { "> { snapshot.forEach((doc) => { const newProduct = { id: doc.id, ...doc.data(), }; if (index === 0) { products.push(newProduct); } else { savingbaseList.push(newProduct); } }); }); optionListSnapshots.forEach((snapshot, index) => { snapshot.forEach((doc) => { const newProduct = { "> { snapshot.forEach((doc) => { const newProduct = { id: doc.id, ...doc.data(), }; if (index === 0) { products.push(newProduct); } else { savingbaseList.push(newProduct); } }); }); optionListSnapshots.forEach((snapshot, index) => { snapshot.forEach((doc) => { const newProduct = { ">
const handleButtonClick = async () => {
const baseListPromises = [
getDocs(collection(db, "DEPOSIT_BASE_LIST")),
getDocs(collection(db, "SAVING_BASE_LIST")),
];
const optionListPromises = [
getDocs(collection(db, "DEPOSIT_OPTION_LIST")),
getDocs(collection(db, "SAVING_OPTION_LIST")),
];
const [baseListSnapshots, optionListSnapshots] = await Promise.all([
Promise.all(baseListPromises),
Promise.all(optionListPromises),
]);
const products = [];
const depositOptionalList = [];
const savingbaseList = [];
const savingoptionalList = [];
baseListSnapshots.forEach((snapshot, index) => {
snapshot.forEach((doc) => {
const newProduct = {
id: doc.id,
...doc.data(),
};
if (index === 0) {
products.push(newProduct);
} else {
savingbaseList.push(newProduct);
}
});
});
optionListSnapshots.forEach((snapshot, index) => {
snapshot.forEach((doc) => {
const newProduct = {
id: doc.id,
...doc.data(),
};
if (index === 0) {
depositOptionalList.push(newProduct);
} else {
savingoptionalList.push(newProduct);
}
});
});
setProducts(products);
setdepositOptionalList(depositOptionalList);
setSavingbaseList(savingbaseList);
setSavingoptionalList(savingoptionalList);
};
useEffect(() => {
handleButtonClick();
}, []);
여러개의 비동기 함수 사용시 **Promise.all()**사용한다.
위 코드에서는 먼저 getDocs 함수 호출을 병렬로 실행하기 위해 Promise.all() 메서드를 사용하여 배열에 각각의 프로미스를 담아줍니다. 그리고 Promise.all() 메서드를 다시 한 번 사용하여 모든 배열의 프로미스가 완료될 때까지 대기하고, 모든 결과를 한 번에 처리합니다.
또한, 각각의 결과 배열을 다시 순회하면서 적절한 배열에 결과를 저장하고, 마지막으로 set 함수를 사용하여 state 값을 업데이트합니다.