DEV Community

Nguyen
Nguyen

Posted on

2 2

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay