i18next / i18next-express-middleware

[deprecated] can be replaced with i18next-http-middleware
https://github.com/i18next/i18next-http-middleware
MIT License
206 stars 52 forks source link

changeLanguage does not work as expected #193

Closed javierguzman closed 5 years ago

javierguzman commented 5 years ago

Hello all,

I am building a React App where I use react-i18next. I have a dropdown menu where I click and call changeLanguage which triggers the change of language of the front-end.

Moreover, my API server (Node js/Express) will not realize a change of language has occurred. Therefore I have placed a route "/change-language" that is handled in Express and I call i18next.changeLanguage on the server side:

app.post("/change-language", (req, res) => {
  const language = req.sanitize(req.body.language);
  i18next.changeLanguage(language, (err, t)=>{
    if(err){      
      logger.error(err);
    }
    console.log(i18);
    return res.status(200).send({});
  });
});

This seems to change the language (based on i18next.language) but when I call req.t it continues translating into the old language. I assume I need to use the new t given in the callback, but how do I update the general one so the future requests for this session have the correct t function?

Thank you in advance, Javier

jamuhl commented 5 years ago

Might not be obvious...but to "sync" languages client <-> server you will have to enable cache of language both on client and server:

client: https://github.com/i18next/i18next-browser-languageDetector#detector-options server: https://github.com/i18next/i18next-express-middleware#detector-options

let caches option include cookie

javierguzman commented 5 years ago

Hello Jan!

Thanks for the quick response. Indeed now it works! Actually, at the end I managed to make it work setting the cookie myself with the route path I placed, however with the cache on both sides there is no need for having that path, it works "automatically". I close this.