T
T
TheSerKat2021-04-21 14:18:23
API
TheSerKat, 2021-04-21 14:18:23

How to insert i18next.language into Accept-Language API?

It is necessary to get what language is currently on the site and send the API, in Accept-Language write down what language is now.
When the site loads, requests to the server immediately go and the problem is that i18next.language is initially undefined.
You need to somehow wait until i18next is initialized and only then send requests to

api.js

import * as axios from 'axios'
import i18next from 'i18next';

const instance = axios.create({
    baseURL: 'https://api/',
    headers: {
        'Accept-Language':  i18next.language
    }
})


i18n.js
import i18n from 'i18next'
import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
import { initReactI18next } from 'react-i18next'

i18n
    .use(Backend)
    .use(LanguageDetector)
    .use (initReactI18next)
    .init({
        fallbackLng: 'ru',
        debug: true,
        ns: ["translation", "Header", "MainSlider", "Centers", "Purpose", "Contact"],
        defaultNS: 'translation',
        react: {
            useSuspense: true,
            wait: true
        },
        interpolation: {
            escapeValue: false
        }
    })

export default i18n;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
ReactLover, 2021-04-21
@TheSerKat

instance.interceptors.request.use(config => {
  config.headers['Accept-Language'] = i18next.language;
  return config;
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question