[TIL] 230810

이세령·2023년 8월 10일
0

TIL

목록 보기
80/118

React Router DOM

useLocation

문서 url: https://reactrouter.com/en/main/hooks/use-location
문서에 따르면 위치가 변경될 때 주로 사용한다고 하지만, 현재 pathname을 사용하기 위해 활용하였다.

자유, 학습 게시판

카테고리에 따라 다른 게시물들이 출력되도록 수정해주었다.

동작

현재 url에 따라 queryKey 값을 다르게 초기화해주고 url에 따라 column의 카테고리에서 자유 or 학습 카테고리에 따라 필터링된 데이터를 검색하여 가져오도록 요청한다.

api

const getPosts = async (pageParam: number = 1, param?: string): Promise<ToTalDataType> => {
  let data: any = [];
  let count = null;

  if (param === '/free') {
    const freePosts = await supabase
      .from('post')
      .select('*')
      .eq('category', '자유')
      .range(pageParam * 10 - 10, pageParam * 10 - 1);

    data = freePosts.data;

    const { count: freeCount } = await supabase.from('post').select('count', { count: 'exact' }).eq('category', '자유');

    count = freeCount;
  } else if (param === '/study') {
    const studyPosts = await supabase
      .from('post')
      .select('*')
      .eq('category', '학습')
      .range(pageParam * 10 - 10, pageParam * 10 - 1);

    data = studyPosts.data;

    const { count: studyCount } = await supabase
      .from('post')
      .select('count', { count: 'exact' })
      .eq('category', '학습');

    count = studyCount;
  } else {
    const allPosts = await supabase
      .from('post')
      .select('*')
      .range(pageParam * 10 - 10, pageParam * 10 - 1);

    data = allPosts.data;

    const { count: allCount } = await supabase.from('post').select('count', { count: 'exact' });
    count = allCount;
  }

  // 총 페이지 개수 계산
  const total_pages = count ? Math.floor(count / 10) + (count % 10 === 0 ? 0 : 1) : 1;

  return { posts: data as PostType[], page: pageParam, total_pages, total_results: count };
};

ts에서는 매개변수가 꼭 들어가야 하기 때문에 js성질을 유지하기 위해 ?를 매개변수에 붙여서 꼭 들어가지 않아도 동작하게 만들어 ull값이 들어올 때 오류가 발생하지 않도록 만들어줬다.
url에 따라 학습, 자유일 경우에 각각의 데이터를 검색해서 가져오도록 수정해주었다.

Mainposts.tsx

const navigate = useNavigate();
  const { pathname } = useLocation();
  const queryKey = pathname === '/' ? ['posts'] : pathname === '/free' ? ['freeposts'] : ['studyposts'];

  const {
    data: posts,
    isLoading,
    isError,
    hasNextPage,
    fetchNextPage,
    isFetchingNextPage
  } = useInfiniteQuery<ToTalDataType>({
    queryKey: queryKey,
    queryFn: ({ pageParam }) => getPosts(pageParam, pathname),
    getNextPageParam: (lastPage) => {
      // 전체 페이지 개수보다 작을 때 다음 페이지로
      if (lastPage.page < lastPage.total_pages) {
        return lastPage.page + 1;
      }
    }
  });

useLocation을 사용하여 경로를 확인하고 url에 따라 queryKey가 다른 값이 들어가 동작하도록 수정해주었다.

Firestore 엑세스 만료

규칙 설정 -> 기간 변경 및 지우기

CSS

flex-direction

  • row
    가로
  • column
    세로

infinite query의 동작원리를 어느정도 이해하고 나니 다른 경우에서도 같은 로직을 사용할 수 있었다. 오늘도 동작원리와 알고리즘의 중요성을 깨닫고 간다. 마지막으로 css 마무리하고 팀원들의 코드를 이해하고 버그만 수정하면 될 것 같다.

profile
https://github.com/Hediar?tab=repositories

0개의 댓글