score:0

Accepted answer
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import backend from 'i18next-http-backend';
import api from "../api";

 var lang=navigator.language;

let loadResources= apiDelegate.getTranslations(lang);
const backendOptions = {
  loadPath: 'http://localhost:8080/code/'+lang, 
  request: (options, url, payload, callback) => {
    try {
      loadResources.then((result) => {
        callback(null, {
          data: result,
          status: 200, 
        });
      });
    } catch (e) {
      console.error(e);
      callback(null, {
        status: 500,
      });
    }
  },
};

i18n
  .use(LanguageDetector)
  .use(backend)
  .init({
    backend: backendOptions,
    fallbackLng: "fr",
    debug: false,
    load:"languageOnly",
    ns: ["translations"],
    defaultNS: "translations",
    keySeparator: false, 
    interpolation: {
      escapeValue: false, 
      formatSeparator: ","
    },
    react: {
      wait: true
    }
});
i18n.changeLanguage(navigator.language);
export default i18n;

score:1

import React, { useState } from "react";
import i18next from 'i18next';

function App(){
  const [result,setResult] = useState('')

  getTranslationFromAPi().then( response => {
    i18next
    .init({
      resources: {
        en: response, //Here I need to assign output
      },
      fallbackLng: 'fr',
    });
    i18next.changeLanguage(navigator.language);
  })
  
  //Mock funtion gives response after 5sec
  function getTranslationFromAPi(){
    return new Promise((resolve, rej)=>{
      setTimeout(() => {
        resolve({translation:{ln:'sample lang'}});
      }, 5000);
    })
  }

  setTimeout(() => {
    setResult(i18next.t('ln'))
  }, 10000);

  return(
    <div>
      {/* Result will come after 10 sec */}
      {result}  
    </div>
  )
}

export default App;

score:1

//import request from "request"; deprecated

export const getTranslations = () => {
  var token = sessionStorage.getItem("jwt");
  if (token == null) {
    token = "";
  }

  // return fetch(baseUrl.api + '/file_download/en', {  //when using api
  return fetch(
    //remove line when using api
    "./translation.json" //remove line when using api
    /*     , {   //when using api
    method: 'post',
    headers: new Headers({
      'Authorization': "Bearer " + token,
      "Content-Type": "application/json",
      Accept: "application/json"
    }),
    body: 'A=1&B=2'
  } */
  )
    .then((res) => res.json())
    .then((result) => {
      /*       if (result.status === 200) {  //when using api
        return result.body;
      } */
      if (Object.entries(result).length) return result; //remove line when using api

      return { status: -2, message: result.status, data: [] };
    })
    .catch((error) => {
      return { status: -2, message: error.message, data: [] };
    });
};

score:2

import i18next from 'i18next';
import React from 'react';
import TransFile from './TransFile.js';

const LanguageDetector = require('i18next-browser-languagedetector');
const initReactI18next = require('react-i18next');

//API call
apiDelegate.getTranslations().then((result) => {
  var output;
  output = JSON.stringify(result);
  alert("output1 =>"+result);

  //Moved the assigning logic here
  i18next
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources: {
      en: output, //Here I need to assign output
    },
    fallbackLng: 'fr',
  });
   console.log('Output set to en', output)
  i18next.changeLanguage(navigator.language);
});

export default i18next;

Related Query

More Query from same tag