DEV Community

Nguyen
Nguyen

Posted on

My react-query clone implementation for dependant API fetching custom hooks

In my current working on React manga website using MangaDEX API, I want to put down some notes

My custom hook for getting a manga detail

function useMangaDetail(mangaId, { enable = true } = {}) {
  const [manga, setManga] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // if false then will not excute
    if (!enable) {
      return; // end it
    }

    (async () => {
      try {
        setLoading(true);
        const result = await mangaApi.get(mangaId);
        setManga(result.data);
      } catch (error) {
        console.log('Failed to fetch manga id=', mangaId, error);
      }

      setLoading(false);
    })();
  }, [mangaId, depEnable]);

  return { manga, loading };
}
Enter fullscreen mode Exit fullscreen mode

In the chapter reading page, we need to get manga info depended on the mangaId fetch from chapter detail data

function ChapterReadPage() {
  const { chapterId } = useParams();
  const { chapter, mangaId: mangaIdOfChapter } = useChapterDetail(chapterId);

  const { manga } = useMangaDetail(mangaIdOfChapter, { enable: !!mangaIdOfChapter });
  const mangaEnTitle = manga?.attributes?.title?.en;

  return (
     ...
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)