Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting NextJS, next-i18next, with-redux, with-redux-saga: "Error: If you have a getInitialProps method in your custom _app.js file..."

I'm trying to connect a functioning NextJS/React app that uses 'with-redux-saga' and 'with-redux' to 'next-i1iN' (https://github.com/isaachinman/next-i18next) -- but when my app boots I get the following error:

Error: If you have a getInitialProps method in your custom _app.js file, you must explicitly return pageProps. For more infor mation, see: https://github.com/zeit/next.js#custom-app

TypeError: Cannot read property 'namespacesRequired' of undefined at Function.getInitialProps (/Users/cerulean/Documents/Projects/PAW-React/node_modules/next-i18next/dist/hocs/app-with-translation.js:94:57) at process._tickCallback (internal/process/next_tick.js:68:7)

But I am returning page props in my _app.js.

// _app.js
 static async getInitialProps({ Component, ctx }) {

    const pageProps = {};
    let temp;

    if (Component.getInitialProps) {
      temp = await Component.getInitialProps({ ctx });
    }
    Object.assign(pageProps, temp);
    return { ...pageProps };
  }

Perhaps there is something wrong with how I am hooking together the various HOCs? In _app.js I have:

export default withRedux(createStore, { debug: false })(withReduxSaga({ async: true })(i18nInstance.appWithTranslation(MyApp)));

And in my index.js I have:

   // index.js
const mapStateToProps = (state) => ({ homeData: getHomePageData(state) });

export default connect(mapStateToProps)(withNamespaces('common')(Index));

Any insights much appreciated!

like image 400
Cerulean Avatar asked Feb 07 '19 13:02

Cerulean


1 Answers

For anyone coming to this issue and wondering what @cerulean meant in his answer.

1) use require instead of import

NextJS doesn't transpile your modules if you use a custom server (more info). Therefore you cannot use import in your next-i18next configuration without going through a vale of tears.

// NextI18NextConfig.js

const NextI18Next = require('next-i18next/dist/commonjs')

module.exports = new NextI18Next({
  defaultLanguage: "en",
  otherLanguages: ["de"]
  // ... other options
});
// server.js

const nextI18next = require("./path/to/NextI18NextConfig");

// ... the rest of your server.js code

This is a mix&match from next-i18next example and documentation


2) keep pageProps as it is

You cannot play too much with getInitialProps returned value. If you need to add extra stuff you should be careful not replacing or manipulating pageProps. See below.

  static async getInitialProps({ Component, ctx }) {
    let pageProps = {}

    const extraStuff = doSomeExtraStuff()

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return { pageProps, extraStuff }
  }

More about it on this thread.

like image 198
a.barbieri Avatar answered Sep 25 '22 15:09

a.barbieri