简体   繁体   中英

Not able to return data from getInitialProps() of lower order page component

I have a lower order page component that needs to fetch data in the getInitialProps(). It successfully fetches the data, but it does return as prop in the component. Below is the code I'm working on

import React, { Component } from 'react';

import DefaultPage from '../hocs/DefaultPage';
import PageLayout from '../components/PageLayout';
import { getJwtFromLocalCookie, getJwtFromServerCookie } from '../utils/auth';

import { getUser } from '../services/users';

class Profile extends Component {
    static async getInitialProps(ctx) {
        let user;
        const jwt = process.browser ? getJwtFromLocalCookie() : getJwtFromServerCookie(ctx.req);
        try {
            const {data} = await getUser(ctx.query.id, jwt);
            user = data;
        }
        catch (err) {
            if(err.code === 404)
                ctx.res.statusCode = 404;
        }
        console.log(user);
        return { user };
    }

    constructor(props) {
        super(props);
        this.state = { user: null };
    }

    render() {
        console.log(this.props);
        return (
            <PageLayout
                active="" 
                loggedUser={this.props.loggedUser}
            >

            </PageLayout>
        );
    }
}

export default DefaultPage(Profile);

The console.log() in the getInitialProps() does display the correct data, but the console.log() in render() doesn't have the user prop.

Ok, I found the solution, turns out in the getInitialProps() of the higher order component the getInitialProps() of the lower order component was returning a promise and needed to be handled

So, below is the before code of my hoc getInitialProps

static getInitialProps (ctx) {
    const loggedUser = process.browser ? getUserFromLocalCookie() : getUserFromServerCookie(ctx.req)
    const pageProps = Page.getInitialProps && Page.getInitialProps(ctx);
    return {
      ...pageProps,
      loggedUser,
      currentUrl: ctx.pathname,
      isAuthenticated: !!loggedUser
    }
  }

And the following is corrected code

static async getInitialProps (ctx) {
    const loggedUser = process.browser ? getUserFromLocalCookie() : getUserFromServerCookie(ctx.req)
    const pageProps = await (Page.getInitialProps && Page.getInitialProps(ctx));
    return {
      ...pageProps,
      loggedUser,
      currentUrl: ctx.pathname,
      isAuthenticated: !!loggedUser
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM