DEV Community

Bruno Santos
Bruno Santos

Posted on Edited on

What is the best way to make nested api calls with React hooks?

I'm using the following approach

useApi hook

import { useState, useCallback } from 'react';

const useApi = (path) => {
  const [data, setData] = useState(undefined);
  const [loading, setLoading] = useState(false);

  const makeRequest = useCallback((params = '') => {
      setLoading(true);
      fetch(`https://apiexample.com${path}${params}`)
        .then((res) => res.json())
        .then((data) => setData(res))
        .catch(() => {})
        .finally(() => setLoading(false));
  }, [path, setData, setLoading]);

  return [{ data, loading }, makeRequest];
};

export default useApi;

use of useApi hook

import React, { useEffect } from 'react';
import useApi from './use-api.js';

const MyPage = () => {
  const [{ data: post }, loadPost] = useApi('/posts/1234');
  const [, loadComments] = useApi('/comments');

  useEffect(() => {
    loadPost();
  }, [loadPost]);

  useEffect(() => {
    if (post) loadComments('?postId=1234');
  }, [post, loadComments]);

  return <h1>Content</h1>;
};

export default MyPage;

But the more nested api calls, more complex the code gets... So, how to avoid this scenario?

Top comments (0)