iT邦幫忙

2023 iThome 鐵人賽

DAY 9
0
Modern Web

前端知識系列 第 20

Custom hook

  • 分享至 

  • xImage
  •  

Custom Hook: useFilterDropdown

Purpose

This custom hook is designed to fetch tag data and handle URL query parameters for filtering in a dropdown menu.

Key Functions

  • useSWR: Fetches tag data based on the locale and tag kind.
  • useEffect: Checks if the data is loaded and if a default filter is set in the URL. If not, it sets the default filter based on the first tag ID.
// useFilterDropdown.js
import useSWR from 'swr';
import { useRouter } from 'next/router';
import { useEffect } from 'react';

export const useFilterDropdown = () => {
  const router = useRouter();
  const { locale } = router;

  const { data: normalTagsData, isLoading: isNormalTagsDataLoading } = useSWR(
    // Fetching logic here...
  );

  useEffect(() => {
    const defaultId = normalTagsData?.[0]?.id;
    const hasFilterQuery = router.query[queryNameMap.get('gameListFilterHotOrNew')];

    if (!isNormalTagsDataLoading && defaultId && !hasFilterQuery) {
      router.push({
        query: {
          ...router.query,
          [queryNameMap.get('gameListFilterHotOrNew')]: defaultId,
        },
      });
    }
  }, [isNormalTagsDataLoading, normalTagsData, router.query]);

  return { normalTagsData, isNormalTagsDataLoading };
};

Component: FilterDropdownGameList

Purpose

This component uses the useFilterDropdown custom hook to fetch and display tag data in a dropdown filter.

import { useFilterDropdown } from './useFilterDropdown';

export function FilterDropdownGameList(prop: FilterDropdownGameListProps) {
  const { normalTagsData, isNormalTagsDataLoading } = useFilterDropdown();

  // Rest of your component logic
}

上一篇
Google cloud storage
下一篇
2023/10/10
系列文
前端知識30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言