Skip to content Skip to sidebar Skip to footer

Accessing Consumed React.Context In Next.js GetInitialProps Using HOC

I am attempting to abstract my API calls by using a simple service that provides a very simple method, which is just an HTTP call. I store this implementation in a React Context, a

Solution 1:

You can't access an instance of your provider in as static method getInitialProps, it was called way before the React tree is generated (when your provider is available).

I would suggest you to save an Singelton of your API in the API module, and consume it inside the getInitialProps method via regular import.

Or, you can inject it to your componentPage inside the _app getInitialProps, something like that:

// _app.jsx
import api from './path/to/your/api.js';

export default class Webshop extends App {
    static async getInitialProps({ Component, router, ctx }) {
        let pageProps = {}
        ctx.api = api;

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

        return { pageProps }
    }

    render () {
        const { Component, pageProps } = this.props

        return (
            <Container>
                <Component {...pageProps} />
            </Container>
        );
    }
}

// PageComponent.jsx

import React, { Component } from 'react';

class Code extends React.Component
{
    static async getInitialProps ({ query, ctx }) {
        const decodedResponse = ctx.api.decode(query.code); // Cannot read property 'api' of undefined

        return {
            code: query.code,
            decoded: decodedResponse
        };
    }

    render () {
        return (
            <div>
                [...]
            </div>
        );
    }
}

export default Code;

Does it make sense to you?


Post a Comment for "Accessing Consumed React.Context In Next.js GetInitialProps Using HOC"