configProvider.tsx 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use client';
  2. import { createContext, useContext, useEffect, useState } from 'react';
  3. import { fetchConfig } from '@/lib/api/system';
  4. import Config from '@/types/config';
  5. const ConfigContext = createContext<Config|null>(null);
  6. // Context Provider
  7. export function ConfigProvider({ children }: { children: React.ReactNode }) {
  8. const [config, setConfig] = useState<Config|null>(null);
  9. const [loading, setLoading] = useState<boolean>(true);
  10. useEffect(() => {
  11. fetchConfig().then((configs) => {
  12. if (configs) {
  13. setConfig(configs.data);
  14. }
  15. }).catch((err) => {
  16. console.error(err);
  17. }).finally(() => {
  18. setLoading(false);
  19. });
  20. }, []);
  21. if (loading) {
  22. return <></>;
  23. }
  24. return (
  25. <ConfigContext.Provider value={config}>
  26. {children}
  27. </ConfigContext.Provider>
  28. );
  29. }
  30. // Context 사용을 위한 커스텀 훅
  31. export function useConfigContext(): Config {
  32. const context = useContext(ConfigContext);
  33. if (context === null) {
  34. throw new Error('useConfigContext는 ConfigProvider 내부에서만 사용 가능합니다.');
  35. }
  36. return context;
  37. }