본문 바로가기
스파르타코딩클럽/내일배움캠프

[TIL] 내일배움캠프 React 과정 2023.01.01_Firebase CRUD

by heereal 2023. 1. 1.

Today I Learned

  • Firebase를 투두리스트 CRUD와 연동하기

 


firebaseConfig.js

더보기
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Optionally import the services that you want to use
// import {...} from "firebase/auth";
// import {...} from "firebase/database";
import {getFirestore} from "firebase/firestore";
// import {...} from "firebase/functions";
// import {...} from "firebase/storage";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AIzaSyAGekz905CxyAPdaiOx3uNQDKlSX6h9ktI",
  authDomain: "to-do-list-native.firebaseapp.com",
  projectId: "to-do-list-native",
  storageBucket: "to-do-list-native.appspot.com",
  messagingSenderId: "218362722375",
  appId: "1:218362722375:web:4efa6d1bd4d61b000b1962"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export {db};

 

Firestore 데이터 읽기

// todos가 변경될 때마다 데이터 새로 불러오기
useEffect(() => {
	getTodos();
}, [todos]);
 
// firebase에서 데이터 가져오기
const getTodos = async () => {
    const array = [];
    const querySnapshot = await getDocs(collection(db, "todos"));
    querySnapshot.forEach((doc) => array.push({docId: doc.id,...doc.data()}));
    setTodos(array)
};

데이터를 불러와서 콘솔로 찍는 것까지는 성공했었는데 가져온 데이터를 어떻게 화면에 보여줘야 될까를 해결하지 못했었다. 그런데 다른 분과 이에 대해 의견을 나누다가 array를 만들어서 forEach문으로 push를 해주는 방법이 있다는 것을 알게 됐다! 그래서 완성된 array를 다시 todos에 담는다. array.push를 할 때 나중에 수정, 삭제할 때 이용하기 위해 firestore 각 문서의 id가 필요하기 때문에 spread를 이용해서 각 객체에 dos.id(문서의 id)까지 함께 넣어 주었다. 그리고 todos가 변할 때마다 데이터를 바로 업데이트해주기 위해서(새로 데이터를 불러오기 위해서) useEffect를 사용했다.

 

 

Firestore 데이터 추가

// firestore에 데이터 추가하기
const addTodo = async () => {
    const neWTodo = {
      id: Date.now(),
      text,
      isDone: false,
      isEdit: false,
      category
    };
    await addDoc(collection(db, "todos"), neWTodo);
    // setTodos([...todos, neWTodo]);
    setText("");
};

데이터 추가하기는 쉽다. addDoc을 이용해서 추가하려는 객체를 넘기면 된다.

 

 

Firestore 데이터 수정

// firestore 데이터 수정
const editTodo = async (id) => {
    const switchTodo = todos.find((todo) => todo.docId === id); 
    const todoRef = doc(db, "todos", id);
    await updateDoc(todoRef, {
      text: editText,
      isEdit: false
    });
};

<TouchableOpacity onPress={() => deleteTodo(todo.docId)}>
</TouchableOpacity>

삭제 버튼을 클릭했을 때 데이터를 가져올 때 객체마다 저장한 docId를 넘겨서 updateDoc으로 데이터를 수정한다. updateDoc을 이용할 때는 수정하려는 특정 필드의 값만 넘기면 된다.

 

 

Firestore 데이터 삭제

// [삭제] 아이콘 클릭 시 작동-firestore 데이터 삭제
const deleteTodo = (id) => {
    Alert.alert("삭제", "정말 삭제하시겠습니다?", [
      {text: "취소", 
      style: "caneel"},
      {text: "삭제", 
      style: "destructive", 
      onPress: () => {
        deleteDoc(doc(db, "todos", id));
      }}
    ])
};

deleteDoc도 버튼을 클릭했을 때 docId를 넘겨야 이것을 이용해서 삭제할 수 있다.

 


회고

1월 1일 자정에 zep에서 2023년을 맞이하고 바로 새벽 3시까지 firebase 연결하느라 달렸다. 혼자라면 힘들었겠지만 나와 같은 열정을 가진 동기분이 계셔서 즐거운 시간이었다. ㅋㅋ 그래서 투두리스트에 firebase 연결하는 과제는 완료~

 

오늘은 2시부터 시작된 팀플 회의가 밤 10시를 넘어서까지 계속되었다. 아무래도 기초를 탄탄히 쌓고 시작하려다보니 오랜 시간이 걸린 거 같다. 내일 역할 분담까지 하고 나면 드디어 코드를 짤 수 있을 거 같다! 오늘 와이어 프레임이랑 폴더 구조까지 만들면서 우리가 이걸 구현할 수 있을지, 할 수 있다면 어떤 방법을 이용해야 할지 얘기를 많이 나누었는데 일단은 최소한의 기능을 목표로 잡고 진행하기로 했다. 내배캠이 끝나기 전까지 만날 수 있는 날짜를 계산해 봤는데 중간중간 본과정 팀플이 진행되기 때문에 우리에게 주어진 시간이 많이 없다. 그렇더라도 열심히 노력해서 멋진 결과물을 만들어 내고 싶다!

댓글