getInitialProps returning undefined

Viewed 306

I'm using getInitialProps on _app to grab cookies and pass the values down to a component to set an element's width, but it's always sending undefined.

Here is the _app page where I'll be fetching the cookies

// _app.tsx -> page 

function MyApp({ Component, pageProps }: AppProps) {
    return ( 
        <Layout {...pageProps}> 
            <Component {...pageProps} /> 
        </Layout>   
    ); 
}

MyApp.getInitialProps = async (appContext) => { 
    const pageProps = App.getInitialProps(appContext); 
    const { req } = appContext.ctx; 
    const cookies = parseCookies(req); 

    return { 
        ...pageProps, 
        initialAsideLeftHandler: cookies.asideLeftHandler   
    }; 
}
export default MyApp;

Pass it down to layout component for further use in asideLeft component

// Layout.tsx -> component 

interface Props {
  initialAsideLeftHandler: {
    x: number, 
    y: number, 
    width:number, 
    height:number
  }, 
  children: JSX.Element[] | JSX.Element
}

const Layout = (props: Props) => {
  const { children } = props;
  const [isAsideRightOpen, setIsAsideRightOpen] = useState(true);

  return (
    <>
          <AsideLeft initialAsideLeftHandler={props.initialAsideLeftHandler}>
</AsideLeft>
    /* everything else */
    <>
    )
}

Component where I'll be using the fetched cookies from server but unfortunately as I parse it, it returns an error: Unexpected token u in JSON at position 0

// asideLeftHandler.tsx -> component 

function AsideLeft({initialAsideLeftHandler}) {
  const router = useRouter();
  const state = JSON.parse(initialAsideLeftHandler)
  const [asideLeftHandler, setAsideLeftHandler] = useState(JSON.parse(initialAsideLeftHandler)); // ---> line of error: Unexpected token u in JSON at position 0

  useEffect(() => {
    Cookie.set("asideLeftHandler", JSON.stringify(asideLeftHandler), { expires: 7});
  }, [asideLeftHandler]);

    return (
        <Resizeable
            width={asideLeftHandler.width}
        >
        /* everything else */
    )
}
1 Answers

Your _app should be like this

function MyApp({ Component, pageProps, initialAsideLeftHandler }: AppProps) {
    return ( 
        <Layout initialAsideLeftHandler={initialAsideLeftHandler}> 
            <Component {...pageProps} /> 
        </Layout>   
    ); 
}

MyApp.getInitialProps = async (appContext) => { 
    const pageProps = App.getInitialProps(appContext); 
    const { req } = appContext.ctx; 
    const cookies = parseCookies(req); 

    return { 
        ...pageProps, 
        initialAsideLeftHandler: cookies.asideLeftHandler  
    }; 
}
Related