LoadingContext.tsx 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // src/context/LoadingContext.tsx
  2. import React, { createContext, useContext, useState, ReactNode } from 'react';
  3. import { Loading } from '@alifd/next';
  4. interface LoadingContextType {
  5. showLoading: (message?: string) => void;
  6. hideLoading: () => void;
  7. isLoading: boolean;
  8. }
  9. const LoadingContext = createContext<LoadingContextType | undefined>(undefined);
  10. export const LoadingProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  11. const [isLoading, setIsLoading] = useState(false);
  12. const [message, setMessage] = useState<string>('');
  13. const showLoading = (message = '') => {
  14. setMessage(message);
  15. setIsLoading(true);
  16. };
  17. const hideLoading = () => {
  18. setIsLoading(false);
  19. setMessage('');
  20. };
  21. return (
  22. <LoadingContext.Provider value={{ showLoading, hideLoading, isLoading }}>
  23. <Loading visible={isLoading} fullScreen tip={message}>
  24. {children}
  25. </Loading>
  26. </LoadingContext.Provider>
  27. );
  28. };
  29. export const useLoading = () => {
  30. const context = useContext(LoadingContext);
  31. if (!context) {
  32. throw new Error('useLoading must be used within a LoadingProvider');
  33. }
  34. return context;
  35. };