Recoil과 React Query로 firestore 데이터 받아오기

김민우·2023년 3월 6일
0

스파르타 내배캠4기

목록 보기
70/73

팀원들과 프로젝트를 진행하면서 데이터를 관리를 해야할 필요성을 느꼈다.

1. props drilling이 일어나는 곳이 부분적으로 있다.

2. 불필요한 컴포넌트에서 데이터가 호출 된다.

이러한 이유로 데이터를 useQuery로 받아오고 그 데이터를 전역으로 관리하면 어떨까하는 생각과 함께 결론은 내리게 되었다.

1. Custom Hook을 이용한 데이터 받아오기

import { collection, getDocs, query, where } from 'firebase/firestore';
import { authService, db } from '../common/firebase';
import { useQuery } from 'react-query';

const useUser = () => {
  return useQuery(
    'users',
    async () => {
      const q = query(
        collection(db, 'user'),
        where('uid', '==', authService.currentUser.uid),
      );
      const querySnapshot = await getDocs(q);
      const posts = querySnapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
      }));
      return posts;
    },
    {
      cacheTime: 5 * 60 * 1000,
      staleTime: 2 * 60 * 1000,
    },
  );
};

export default useUser;

2. atom으로 저장소 설정

import { atom } from 'recoil';

const userState = atom({
  key: 'userState',
  default: null,
});

export default userState;

3. App 최상단에 적용

function App() {
  const setUserState = useSetRecoilState(userState);
  
  useEffect(() => {
    setUserState(user.data);
  }, [user.data]);
profile
개발자로서 한걸음

0개의 댓글