[TIL] 내배캠4기-React Native-64일차

hare·2023년 1월 3일
0

내배캠-TIL

목록 보기
46/75
  • defaultValue
  • firebase CRUD
  • addDoc / setDoc - id 생성 차이

참고블로그

* 파이어베이스 CRUD 참고 블로그 1
* 파이어베이스 CRUD 참고 블로그 2

defaultValue

defaultValue: 초기값을 지정
(input 태그에서 처음에 보여줄 값)
해당 태그에서 수정이 일어나면 변경된 값으로 보여준다.

지원하는 태그 : <select>,<textarea>,<textInput>・・・・・

* defaultValue 관련 문서
* 참고 블로그

//Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const dbService = getFirestore(app);`

getFirestore() → Firestore Database

addDoc

addDoc : document id를 자동으로 랜덤값으로 생성해주는 특징

setDoc : addDoc()과 유사하지만 specific한 document id가 필요하다.

firebase 공식 문서 예시

  • set()
import { doc, setDoc } from "firebase/firestore"; 
await setDoc(doc(db, "cities", "new-city-id"), data);
  • add()
import { collection, addDoc } from "firebase/firestore"; 
// Add a new document with a generated id.
const docRef = await addDoc(collection(db, "cities"), {
  name: "Tokyo",
  country: "Japan"
});
console.log("Document written with ID: ", docRef.id);
코드를 입력하세요

(참고) But sometimes there isn't a meaningful ID for the document, and it's more convenient to let Cloud Firestore auto-generate an ID for you. You can do this by calling the following language-specific add() methods

* addDoc(collection(Database, "컬렉션 명", payload)
addDoc은 컬렉션만 지정해도 된다.

ex) addDoc(collection(dbService, "todos"), newTodo)
만약 현재 todos란 컬렉션이 없으면 addDoc 실행시 추가해준다.

Read

query, onSnapshot, getDocs

onSnapshot : data에 변화가 있을 때마다 트리거 된다.

onSnapshot(q, (snapshot) => {
      // q (쿼리)안에 담긴 collection 내의 변화가 생길 때 마다 매번 실행됨
      const newTodos = snapshot.docs.map((doc) => {
        const newTodo = {
          id: doc.id,
          ...doc.data(), // doc.data() : { text, createdAt, ...  }
        };
        return newTodo;
      });
      setTodos(newTodos);
    });
const q = query(
      collection(dbService, "todos"),
      orderBy("createdAt", "asc")
    );

getDocs : 컬렉션으로부터 모든 document들을 가져온다.
getDoc : 도큐멘트를 한 개만 가지고 온다.

const getCategory = async () => {
      const snapshot = await getDoc(
        doc(dbService, "category", "currentCategory") // (firebase, "컬렉션명","파일명(document)")
      ); 

updateDoc

await updateDoc(doc(dbService, "todos", id), {
      text: editText,
      // isEdit 값 false로 변경하는 것 잊지말아요
      isEdit: false,
    });

deleteDoc

ex) deleteDoc(doc(dbService, "todos", id));
doc의 id값만 가져와도 삭제 기능 ok

profile
해뜰날

0개의 댓글