react + Firebase 설치 및 세팅하는 방법 보러가기 👇👇 😊
[Firebase] react + Firebase 설치 방법 및 연동
1. Firebase 프로젝트 생성 우선 firebase에서 프로젝트를 생성해야 합니다. 다음 이미지 순서대로 따라 하시면 프로젝트를 생성할 수 있습니다. firebase 홈페이지 https://firebase.google.com/?hl=ko Firebase | Goo
neuri.tistory.com
1. Create - 단일 문서
addDoc(data)
// 저장하려는 데이터
const data = {...}
const handleCreate = async () => {
const docRef = collection(fireStore, "recipe");
await addDoc(docRef, data).then(() => {
alert("등록되었습니다.");
});
};
데이터를 저장하려고 하면 아래와 같은 에러가 발생할 수 있습니다.
Missing or insufficient permissions.
FirebaseError : Missing or insufficient permissions.
[Firebase] Missing or insufficient permissions. 에러 해결법
데이터를 처음 등록하려고 할 때 자주 발생하는 에러입니다. Firebase 사이트 : https://firebase.google.com/?hl=ko 해당 사이트에 들어가서 데이터베이스 규칙 카테고리에 들어갑시다 Firebase | Google’s Mobile
neuri.tistory.com
1. Create - 여러 문서 한 번에 저장하기
addDoc(data)
사용법 및 코드 설명
1. promises[] 에 promise 객체를 반환하는 비동기 함수(addDoc)를 저장한다.
- addDoc 함수는 Firebase에 문서를 추가하는 비동기 함수입니다.
2. Promise.all(promise)에 해당 배열을 넣고 비동기 병렬 처리한다.
- Promise.all(promise)는 promise[]에 있는 모든 프로미스가 완료될 때까지 기다리는 새로운 프로미스를 반환합니다. 이렇게 하면 모든 비동기 작업이 병렬로 처리됩니다. 따라서 FireStore에 있는 모든 문서가 한 번에 저장됩니다.
3. 마지막 비동기 처리까지 정상적으로 처리되면 실행될 코드를 then()에 작성한다.
- then() 메소드는 Promise.all()의 프로미스가 이행될 때 호출됩니다.
// 여러 문서 한번에 저장하기
const data = [
{name:"A",like:0},
{name:"B",like:0},
{name:"C",like:0},
...
]
// Promise.all()로 비동기 병렬 처리하기
const handleCreate = () => {
const docRef = collection(fireStore, "recipe");
const promises: any = [];
data.forEach((recipe) => promises.push(addDoc(docRef, recipe)));
Promise.all(promises).then(() => {
alert("등록 끝!!");
});
};
2. Read - 여러 문서 조회하기
getDocs(docRef)
const getRecipes = async () => {
const docRef = collection(fireStore, 'recipe');
const q = query(docRef, orderBy('like', 'desc')); // 조건
const querySnapshot = await getDocs(q);
const data: any = querySnapshot.docs.map((doc) => {
console.log(doc.data())
const { recipe } = doc.data();
return {
id: doc.id,
recipe : recipe,
...,
};
});
};
2. Read - 단일 문서 조회하기
getDocs(docRef)
const docRef = doc(fireStore,'recipe');
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
const data = docSnap.data();
console.log('Document data: ', data);
} else {
console.log('No document!');
return false;
}
3. Delete - 문서 삭제하기
deleteDoc(doc.id)
ingredients 필드가 없는 문서 삭제하기
name이 계란피자인 문서가 ingredients 배열이 빠진 상태로 등록되었습니다. 해당 문서의 id를 찾아 없애보도록 하겠습니다.
1. ingredients가 undefined인 문서 찾기
const getRecipes = async () => {
const docRef = collection(fireStore, "recipe");
const q = query(docRef);
const querySnapshot = await getDocs(q);
const data: any = querySnapshot.docs.map((doc, index) => {
if (doc.data().ingredients == undefined) {
const id = doc.id; // 문서의 ID 가져오기
const ingredients = doc.data().ingredients;
console.log(id);
console.log(ingredients);
}
});
};
2. 해당 문서의 id를 찾아 삭제하기
const getRecipes = async () => {
const docRef = collection(fireStore, "recipe");
const q = query(docRef);
const querySnapshot = await getDocs(q);
// recipe 전체를 조회하면서 ingredients가 undefined인 문서의 id를 찾아 삭제
const data: any = querySnapshot.docs.map((doc, index) => {
if (doc.data().ingredients == undefined) {
const id = doc.id;
const ingredients = doc.data().ingredients;
deleteRecipe(id);
}
});
};
// 삭제
const deleteRecipe = async (id: string) => {
const docIdRef = doc(fireStore, "recipe", id);
await deleteDoc(docIdRef);
};
4. Update - 문서 필드 수정하기
updateDoc(doc, fieldValue)
like필드가 없는 경우 like = 10 추가해 보기
const getRecipes = async () => {
const docRef = collection(fireStore, "recipe");
const q = query(docRef);
const querySnapshot = await getDocs(q);
const data: any = querySnapshot.docs.map((doc, index) => {
if (!doc.data().hasOwnProperty("like")) {
console.log(doc.data());
}
});
};
const getRecipes = async () => {
const docRef = collection(fireStore, "recipe");
const q = query(docRef);
const querySnapshot = await getDocs(q);
// recipe를 전체 조회하면서 like 필드가 없는 문서에 like = 15 저장
const data: any = querySnapshot.docs.map((doc) => {
if (!doc.data().hasOwnProperty("like")) {
const recipeId = doc.id;
updateRecipe(recipeId, 15);
}
});
};
const updateRecipe = async (id: string, recipeLike: number) => {
const docIdRef = doc(fireStore, "recipe", id);
const newField = { like: recipeLike };
await updateDoc(docIdRef, newField);
};
참고
https://yihoeyiho.tistory.com/91
https://velog.io/@wlsdnjs156/React-Firebase-CRUD
'📝 Firebase' 카테고리의 다른 글
[Firebase] Missing or insufficient permissions. 에러 해결법 (0) | 2024.04.14 |
---|---|
[Firebase] react + Firebase 설치 방법 및 연동 (0) | 2024.04.09 |