4

In my React app, I am using RTK query to fetch data. I have 10+ API endpoints and a route for each one of the endpoints.

I want to show a horizontal line at the top of the page to indicate that the data fethcing is going on.

At the moment, I have done this.

const ArticlePage = () => {
  const { id} = useParams();
  const { data, isFetching, isLoading } = useFetchArticleByIdQuery(id);

  return (
    <Layout>
      {(isFetching || isLoading) && <LinearProgressIndicator />}
      <PageHead />
      {data && <ArticleContent article={data} />}
    </Layout>
  );
};

I have also tried this.

const ArticlePage = () => {
  const { id} = useParams();
  const { data, isFetching, isLoading } = useFetchArticleByIdQuery(id);

  return (
    <Layout>
      <LinearProgressIndicator shouldDisplay={(isFetching || isLoading)} />
      <PageHead />
      {data && <ArticleContent article={data} />}
    </Layout>
  );
};

It is cumbersome ot use the same thing on all the 10+ routes. So is there any way to show <LinearProgressIndicator /> once for all the 10+ endpoints?

mahan
  • 12,366
  • 5
  • 48
  • 83

1 Answers1

7

You can write a selector for that:

  const isLoading = useAppSelector((state) => {
    return Object.values(state.api.queries).some((query) => {
      return query && query.status === QueryStatus.pending;
    });
  });
mahan
  • 12,366
  • 5
  • 48
  • 83
phry
  • 35,762
  • 5
  • 67
  • 81
  • can it be shared via useQuery? – tarek noaman Nov 16 '22 at 14:24
  • If you call useQuery for the same endpoint with the same argument, `isFetching` for that endpoint/argument combination will be shared across components. – phry Nov 16 '22 at 14:41
  • can we separate isLoading and isFetching states in the similar manner? For instance, I need an overlay loader when table has no data but as we paginate I want to show a more subtle loading indicator within the table. – Oleksandr Fomin Apr 19 '23 at 09:32
  • 1
    @OleksandrFomin no, as `isLoading` only exists on component level - answering the question if *this component* ever had data before. That's not known globally. `isFetching` is equal to `QueryStatus.pending`. – phry Apr 19 '23 at 10:45