Property ‘store’ does not exist on type ‘NextPageContext’

Total
1
Shares

We are trying to move our NextJs project from JS to TS and while doing so I encountered following problem.

getInitialProps in my _app.tsx goes something like this:

    static async getInitialProps({ router, ctx, Component }) { 
    const { req, isServer, store, res, query } = ctx;
    let pageProps = {};
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }
    return { pageProps, isServer, router, store };
  }

But when I try to access store in a functional component like:

SupportHome.getInitialProps = async ({ query, store, isServer }) => {
  store.dispatch(getCategory());
  return {
    isServer,
    store
  };
};

It throws the following error:
Property ‘store’ does not exist on type ‘NextPageContext’ and Property ‘isServer’ does not exist on type ‘NextPageContext’
Can anyone help me with this?


Solution

Fixed the issue. Basically NextPageContext has following fields defined in it’s interface:

export interface NextPageContext {
    /**
     * Error object if encountered during rendering
     */
    err?: (Error & {
        statusCode?: number;
    }) | null;
    /**
     * `HTTP` request object.
     */
    req?: IncomingMessage;
    /**
     * `HTTP` response object.
     */
    res?: ServerResponse;
    /**
     * Path section of `URL`.
     */
    pathname: string;
    /**
     * Query string section of `URL` parsed as an object.
     */
    query: ParsedUrlQuery;
    /**
     * `String` of the actual path including query.
     */
    asPath?: string;
    /**
     * `Component` the tree of the App to use if needing to render separately
     */
    AppTree: AppTreeType
}

So I simply extended the interface in my _app.tsx. Something like this:

import {Store} from "redux";

export interface MyPageContext extends NextPageContext {
  store: Store;
  isServer: boolean;
}

And now whenever I have to use getInitialProps in any functional component I call it like this:

HelpDesk.getInitialProps = async (props: MyPageContext) => {
  const { query, store } = props;
  store.dispatch(getCategory());
  return { query };
};

Took inspiration from here

Leave a Reply

Your email address will not be published. Required fields are marked *