File "useLanguage.ts"

Full Path: /home/trinadezambia/public_html/student_panel/src/useLanguage.ts
File size: 2.68 KB
MIME-type: text/x-java
Charset: utf-8

'use client';

import { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '@/components/store';
import {
  setLanguage,
  setTranslations,
  setLoading,
  setError,
  rehydrateLanguage,
  LanguageCode,
} from '@/components/store/slices/languageSlice';

/**
 * Custom hook to manage language state and translations
 * Handles loading translations when language changes
 *
 * @returns Language state and functions to change language
 */
export function useLanguage() {
  const dispatch = useAppDispatch();

  // Get language state from Redux store
  const {
    currentLanguage,
    currentLanguageName,
    languages,
    translations,
    loading,
    error,
  } = useAppSelector((state) => state.language);

  // Rehydrate language from localStorage on mount
  useEffect(() => {
    dispatch(rehydrateLanguage());
  }, [dispatch]);

  // Load translations when language changes
  useEffect(() => {
    const loadTranslations = async () => {
      // Set loading state before fetching translations
      dispatch(setLoading(true));

      try {
        let translationModule;
        // Use dynamic import with template literal to load the appropriate translation file
        // This makes it easy for non-IT persons to add new languages by just adding a JSON file
        try {
          translationModule = await import(
            `@/lib/student/translations/${currentLanguage}.json`
          );
        } catch {
          console.error(`Could not find translation file for ${currentLanguage}, falling back to English`);
          // Fallback to English if the specific language file doesn't exist
          translationModule = await import(
            '@/lib/student/translations/en.json'
          );
        }

        // Set translations from the imported module
        const translationsData = translationModule.default || translationModule;
        dispatch(setTranslations(translationsData));
        dispatch(setLoading(false));
      } catch (error) {
        console.error(
          `Failed to load translations for ${currentLanguage}:`,
          error
        );
        dispatch(setError('Failed to load translations'));
      }

    };

    // Load translations every time the language changes
    // This ensures translations are updated when the user switches languages
    if (currentLanguage) {
      loadTranslations();
    }
  }, [currentLanguage, dispatch]);

  /**
   * Change the current language
   * @param lang - The language code to switch to
   */
  const changeLanguage = (lang: LanguageCode) => {
    dispatch(setLanguage(lang));
  };

  return {
    currentLanguage,
    currentLanguageName,
    languages,
    translations,
    loading,
    error,
    changeLanguage,
  };
}