[리팩토링] 왜 식물 리스트 최신화가 안 이루어지는가?

2023. 9. 15. 14:01Project Tours/Tour on Plantopia

분명 삭제, 생성 로직은 문제가 없었는데 생성하고 navigate로 메인 리스트로 돌아오는데 생성 때는 문제 없이 리스트가 업데이트 되어 출력되지만 삭제 시에는 데이터는 삭제 되었는데 클라이언트 단에서 업데이트가 안되어있었다. 도대체 왜 그런지 이해를 못하고 있으면서 로직이 잘못 되었나 살피었다. 

 

분명 이 접근이 잘못된 것이 클라이언트 단에서 화면 업데이트 문제인데 데이터 코드를 보았다는 것은 멍청했다.

 

export const deletePlantDataByDocId = async (docId: string) => {
  if (!docId) return;
  // 삭제할 plantData를 먼저 찾고
  const docRef = doc(db, 'plant', docId);
  const plantData = await findPlantDataByDocId(docId);

  // 유저 이메일로 데이터를 받아서 사이즈를 확인해야함, 사이즈가 1이면 그냥 바로 삭제.
  const q = query(
    collection(db, 'plant'),
    where('userEmail', '==', plantData?.userEmail),
  );
  const userPlants = await getDocs(q);

  // 유저가 가지고 있는 plant가 하나인 경우 바로 삭제
  if (userPlants.size === 1) {
    await deleteDoc(docRef);
    successNoti('식물을 삭제하였습니다.');
    return;
  }

  // id로 찾은 식물 데이터가 메인이니? 삭제하고 유저 데이터의 첫 번째 식물을 메인으로 등록
  if (plantData?.isMain == true) {
    try {
      await deleteDoc(docRef);
      const firstPlantDataId = userPlants.docs[0].id;
      const documentRef = doc(db, 'plant', firstPlantDataId);
      const updatedFields = {
        isMain: true,
      };
      await updateDoc(documentRef, updatedFields);
      console.log('메인에서 삭제됨');
      successNoti('식물을 삭제하였습니다.');
      return;
    } catch {
      errorNoti('식물 삭제에 실패 하였습니다.');
      return;
    }
  }
  // 메인이 아니라면 바로 삭제
  else if (plantData?.isMain == false) {
    try {
      await deleteDoc(docRef);
      console.log('메인 아님에서 삭제됨');
      successNoti('내 식물이 삭제 되었습니다.');
      return;
    } catch (error) {
      errorNoti('식물 삭제에 실패 하였습니다.');
      return;
    }
  }
};

역시나 문제가 없다. 파이어 베이스에서도 삭제가 잘된다.

 

그럼 컴포넌트에서 문제가 있다는 것인데 

  const deletePlant = async () => {
    if (docId) {
      await deletePlantDataByDocId(docId);
    }
    navigate('/myplant');
  };

정말 바보 같게도 async를 써놓고 await을 안적어주었다... 왜 에러가 안났는지 의문....

이전에 프론트 코치가 데이터단과 프론트단을 분리해서 고민하라고 했는데 또 같은 실수를 해서 좀 마음이 안좋았다.

await을 안적다보니 데이터 삭제 기다림 없이 그냥 리스트 페이지로 이동했고 당연히 화면에 삭제 데이터가 남아있었다.

이런 실수는 이제 그만할 때가 된 것 같다.