Project

firebase onsnapshot unmount 시키기

ji_su_04 2023. 2. 15. 19:06

onsnapshot은 실시간으로 db 컬렉션에 정보가 업데이트 되면 정보를 새로 받아온다.

그래서 컴포넌트를 벗어났을 때 이것을 해제시켜줘야 하는데 그 방법은 useEffect의 retrun 안에 unsubscribe을 넣어주는 것이다.

 useEffect(() => {
    const q = query(
      collection(dbService, 'profile'),
      //   where('id', '==', authService.currentUser?.uid),
    );
    const unsubscribe = onSnapshot(q, (snapshot) => {
      const newprofiles = snapshot.docs.map((doc) => {
        const newprofile = {
          id: doc.id,
          ...doc.data(),
        };
        return newprofile;
      });
      setProfileInformation(newprofiles);
    });
    return () => {
      unsubscribe();
    };
  }, []);

그럼 컴포넌트를 벗어났을 때 unmount가 가능하다.

반응형