Mighty Eight
Mighty Eight2d ago

Getting global query loading state on client (react)

Is it possible to get the loading state globally for custom functions? For instance, I want to implement navigationprogress (a moving line at the top) when any query loads and finish when it ends. Not sure if it's possible.
1 Reply
Mighty Eight
Mighty EightOP11h ago
Just to answer myself, yes, it is possible. https://discord-questions.trpc.io/m/1069050572185010279 https://tanstack.com/query/latest/docs/framework/react/reference/useIsFetching My code implementation is:
import { useEffect, useRef } from 'react';
import { useIsFetching } from '@tanstack/react-query';
import { nprogress, NavigationProgress } from '@mantine/nprogress';

export function GlobalLoadingIndicator() {

const isFetching = useIsFetching();
const timeoutRef = useRef<NodeJS.Timeout | null>(null);

useEffect(() => {

if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}

if (isFetching > 0) {

timeoutRef.current = setTimeout(() => {
nprogress.start();
}, 100);
} else {

nprogress.complete();
}

return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
};
}, [isFetching]);

return <NavigationProgress />;
}
import { useEffect, useRef } from 'react';
import { useIsFetching } from '@tanstack/react-query';
import { nprogress, NavigationProgress } from '@mantine/nprogress';

export function GlobalLoadingIndicator() {

const isFetching = useIsFetching();
const timeoutRef = useRef<NodeJS.Timeout | null>(null);

useEffect(() => {

if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}

if (isFetching > 0) {

timeoutRef.current = setTimeout(() => {
nprogress.start();
}, 100);
} else {

nprogress.complete();
}

return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
timeoutRef.current = null;
}
};
}, [isFetching]);

return <NavigationProgress />;
}
TRPC global loading page - tRPC
Hey. With trpc/nextjs I'm wondering if its possible to have a global loading context/state which is used across my whole app, whenever a TRPC endpoint .isFetched property is false, it will display a "loading" symbol. Currently I have to do something like this on every page: ```tsx if (!getMailQuery.isFetched) { return ( <AppShel...
useIsFetching | TanStack Query React Docs
useIsFetching is an optional hook that returns the number of the queries that your application is loading or fetching in the background (useful for app-wide loading indicators). tsx import { useIsFetc...

Did you find this page helpful?