ilyalesik/react-fetch-hook

Fetch some data and only then fetch some one

sergey-pimenov opened this issue · 2 comments

Hi! First of all, many thanks for a good tool, I use it in my project and it helps me a lot to keep the code clean.

Recently I needed to fetch some data and only then fetch other data that would be based on the result of the first fetch.

I try something like this. But as I understand it's doesn't working because hooks limitations.

  const { isLoading, data: repoData } = useFetch(`${endpoint.github}repos/${repo}`, {
    headers: new Headers({
      Authorization: `token ${process.env.GITHUB_TOKEN}`,
    })
  });

  if (!isLoading) {
    const userAPIUrl = repoData.owner.url; // Get this staff from another hook

    const { data: userData } = useFetch(`${endpoint.github}users/${userAPIUrl}`, {
      headers: new Headers({
        Authorization: `token ${process.env.GITHUB_TOKEN}`,
      })
    });
  }

Any ideas how I can implement it in a different way? I am not currently a React guru and I would be very grateful for any help in this case.

Hi, Sergey! Thank you, glad that the library is useful to you. 🙂

I recommended to use the depends option at the second useFetch instead of if (!isLoading):

const { isLoading, data: repoData } = useFetch(`${endpoint.github}repos/${repo}`, {
    headers: new Headers({
      Authorization: `token ${process.env.GITHUB_TOKEN}`,
    })
  });

const userAPIUrl = repoData && repoData.owner && repoData.owner.url; 

const { data: userData } = useFetch(`${endpoint.github}users/${userAPIUrl}`, {
  headers: new Headers({
    Authorization: `token ${process.env.GITHUB_TOKEN}`,
  }),
  depends: [userAPIUrl] // users request will not be called until repoData not loaded
});

The depends option was implemented especially for dependent requests.

Exactly what I need, thank you so much!