TIL 24. 01. 17

물품 목록 필터를 구현하는 중에 URL에 따라 API 요청을 보내야 했다. 상태가 URL에 있어 조건부로 쿼리키와 쿼리 함수를 변경하도록 했다.

export const usedGoodsKeys = {
  all: ['used-goods'] as const,
  search: (params: SearchParams) => [...usedGoodsKeys.all, { query: params.query }] as const,
  category: (params: SearchParams) =>
    [...usedGoodsKeys.all, { main: params.main, sub: params.sub }] as const,
  categoryAndSearch: (params: SearchParams) =>
    [...usedGoodsKeys.all, { main: params.main, sub: params.sub, query: params.query }] as const
};

export const getQueryKey = (params: SearchParams) => {
  const { main, sub, query } = params;

  if (query && main && sub) return usedGoodsKeys.categoryAndSearch(params);
  if (query) return usedGoodsKeys.search(params);
  if (main || sub) return usedGoodsKeys.category(params);
  return usedGoodsKeys.all;
};

export const getQueryFunction = (params: SearchParams) => {
  const { main, sub, query } = params;

  if (main && sub && query) return () => getUsedGoodsByKeywordAndCategory(main, sub, query);
  if (main && sub) return () => getUsedGoodsByCategory(main, sub);
  if (query) return () => getUsedGoodsByKeyword(query);
  return getUsedGoods;
};


const UsedGoodsContainer = async ({ searchParams }: { searchParams: SearchParams }) => {
  const [queryKey, queryFn] = [getQueryKey(searchParams), getQueryFunction(searchParams)];
  const queryClient = new QueryClient();
  await queryClient.prefetchQuery({ queryKey, queryFn });

  return (
    <>
      <UsedGoodsFilter params={searchParams} />
      <HydrationBoundary state={dehydrate(queryClient)}>
        <UsedGoodsList />
      </HydrationBoundary>
    </>
  );
};

카테고리:

업데이트:

댓글남기기