nuxt-community / moment-module

Efficient Moment.js integration for Nuxt
MIT License
195 stars 12 forks source link

Locale not working as expected when with i18n routes in generated mode #58

Closed Burtonium closed 2 years ago

Burtonium commented 4 years ago

When using both nuxt-i18n and nuxtjs/moment I ran into an interesting issue that I think deserves the attention of this module. If this is the wrong place for this issue then I apologize.

Essentially, I wanted to globally set the locale as the following plugin:

@/plugins/moment.js

export default ({ app }) => {
  const { $moment } = app;
  $moment.locale(app.i18n.locale);

  app.i18n.onLanguageSwitched = (_oldLocale, newLocale) => {
    $moment.locale(newLocale);
  };
};

When working in universal mode, this works as expected. But, when working in generated mode the dates would flicker with the last locale of the last generated route because moment does not get reinitialized between routes.

Here's an example: https://github.com/Burtonium/moment-test/tree/bug-example https://moment-i18n-bug-example.netlify.com/

You'll see the date flicker in Spanish. If not, throttle your internet in the browser to replicate.

The fix was to only locally use the locale and overriding the moment instance completely and use local instances of moment:

@/plugins/moment.js

export default ({ app }, inject) => {
  const { $moment } = app;
  inject('moment', (...args) => {
    const localMoment = $moment(...args);
    localMoment.locale(app.i18n.locale);
    return localMoment;
  });
};

This fixed everything for me. Not sure if this is the right way to go about it but would like to know your thoughts. Maybe a warning in the documentation with a proposed solution would go a long way and save people some time. Let me know.

ricardogobbosouza commented 4 years ago

Hi @Burtonium Sorry for the delay, but I couldn't reproduce

omarmfs98 commented 4 years ago

thanks for the solution, it worked for me too, personally I see the code very suitable

brunodeangelis commented 4 years ago

This also worked for me, and I find the solution very elegant! Thank you very much

farnabaz commented 3 years ago

This should fix using latest version of Nuxt.

sonnh58 commented 2 years ago

Thanks for your fix