avatar
Understanding the Key Elements of Cloud Services

Guest 136 17th Jan, 2025

'use client'

import i18next, { KeyPrefix, Namespace } from 'i18next'
import resourcesToBackend from 'i18next-resources-to-backend'
import {
  UseTranslationOptions,
  UseTranslationResponse,
  initReactI18next,
  useTranslation as useTranslationOrg,
} from 'react-i18next'
// import LocizeBackend from 'i18next-locize-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { getOptions } from './settings'
import { useEffect } from 'react'
import { getI18NEXTFromLocalStorage } from '@/utils/storage'

// on client side the normal singleton is ok
i18next
  .use(initReactI18next)
  .use(LanguageDetector)
  .use(resourcesToBackend((language: any, namespace: any) => import(`./locales/${language}/${namespace}.json`)))
  // .use(LocizeBackend) // locize backend could be used on client side, but prefer to keep it in sync with server side
  .init({
    ...getOptions(),
    lng: undefined, // let detect the language on client side
    detection: {
      order: ['querystring', 'cookie', 'htmlTag', 'navigator'],
      caches: ['cookie'],
    },
  })

const runsOnServerSide = typeof window === 'undefined'

export function useTranslation<N extends Namespace, TKPrefix extends KeyPrefix<N> = undefined>(
  ns?: N | Readonly<N>,
  options?: UseTranslationOptions<TKPrefix>,
): UseTranslationResponse<N, TKPrefix> {
  const ret = useTranslationOrg(ns, options)

  // const lng = getI18NEXTFromLocalStorage()

  // const { i18n } = ret
  // if (runsOnServerSide && i18n.resolvedLanguage !== lng) {
  //   i18n.changeLanguage(lng)
  // } else {
  //   // eslint-disable-next-line react-hooks/rules-of-hooks
  //   useEffect(() => {
  //     if (i18n.resolvedLanguage === lng) return
  //     i18n.changeLanguage(lng)
  //   }, [lng, i18n])
  // }

  return ret
}
Markup
Description

No description

To share this paste please copy this url and send to your friends
RAW Paste Data