1

I'm trying to integrate formatters generated with globalize npm package into next.js based application. Formatters are stored in locale specific files. Idea is to import locale specific formatters dynamically based on current locale. Current locale information is available via next-i18next integration in getInitialProps method of the page but since formatters contain functions importing formatters in getInitialProps and passing them along with initial props doesn't work.

What would be any potential workaround to achieve desired behaviour?

1 Answers1

0

I ended up using HOC with dynamic imports:

const formatters = {};
LOCALES.forEach((locale) => {
    formatters[locale] = dynamic(() => {
      return import(`../../public/static/globalize/locales/${locale}/formatters-${locale}.js`);
    });
});
    
export default function withFormatter(Page) {
    const PageWithFormatter = (props) => {
    const lang = i18n.language || props.currentLanguage || 'en';
    
    const formatter = formatters[lang]('').type(lang);
    
    return (
      <GlobalizeContext.Provider value={{ formatter }}>
        <Page {...props} />
      </GlobalizeContext.Provider>
    );
  };
    
  PageWithFormatter.getInitialProps = async ({ req }) => {
    const currentLanguage = req ? req.language : '';
    
    return { currentLanguage };
  };
    
  return PageWithFormatter;
}
Renan Ferreira
  • 2,122
  • 3
  • 21
  • 30