0

Forgive me and my lack of understanding, assuming I have gists array with following structure:

{
     "description": 3,
     "id": 123456, 
     "forks_url": "https:api.github.com..."
}

I need to get the list of gists for a user but also query the forks of each gist to be rendered. How can I have the least number of async api calls with maybe Promise.all or any other libraries that might help

I mean, I got it to work at the moment with a fetching the gists and querying for the forks each time but it is making lots of API calls which I'd like to avoid.

const GistData = ({ username }) => {
  React.useEffect(() => {
    if (!username) {
      return;
    }
    setState({ status: 'pending' })
    octokit.request(`GET /users/${username}/gists`, username)
      .then(
        gists => {
          setState({ gists: gists.data, status: 'resolved' })
        },
        error => {
          setState({ error, status: 'rejected' })
        }
      );
  }, [username]);

  if (status === 'resolved') {
    return gists.map(
      gist => <GistCard key={gist.id} gist={gist} username={username} />
    )
  } else {
    throw error
  }
}

export default GistData
const GistCard = ({ gist, username }) => {
  React.useEffect(() => {
    if (!id) {
      return;
    }
    setState({ status: 'pending' });
    octokit.request(`GET /gists/${id}/forks`, id).then(
      (forks) => {
        setState({ forks: forks.data, status: 'resolved' });
      },
      (error) => {
        setState({ status: 'rejected', error });
      }
    );
  }, [id]);

 if (status === 'resolved') {
    return (
      <div className="gist">
       <p>{description}</p>}
        <Tags fileList={files} />
        {forks.length > 0 && (
          <div>
            <h3>Forks: ({forks.length})</h3>
            {forks.map((fork) => (
              <Fork key={fork.id} fork={fork} />
            ))}
          </div>
        )}
      </div>
    );
  } else {
    throw error
  }
};

export default GistCard;
Omar
  • 49
  • 1
  • 6

1 Answers1

0

In my perspective, this is a backend problem.

In the way that the data comes, is not possible for the frontend to create a Promise.All, because you will need the initial call to get the Gist list. After having the list of gist technically you can do the Promise.All, but is the same amount of calls that the way are you currently doing.

Well, I guess you mean to make the get each time you get the gist info. For that, you can contact .then.

.then(gists => {
 setState({ gists: gists.data, status: 'resolved' })
    },
    error => {
      setState({ error, status: 'rejected' })
    }
 return gists.data 
 ).then(data => call fetch fork by each gist);
  • Yes so one call to get the list but my problem is in the forks calls where it's making one call per gist. What I'd like to be able to do is get the forks of each gist, if available then resolve the promise once I have the forks from the backend. – Omar Apr 08 '21 at 06:03