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.jsximport api from'./path/to/your/api.js';
exportdefaultclassWebshopextendsApp {
staticasyncgetInitialProps({ Component, router, ctx }) {
let pageProps = {}
ctx.api = api;
if (Component.getInitialProps) {
pageProps = awaitComponent.getInitialProps(ctx)
}
return { pageProps }
}
render () {
const { Component, pageProps } = this.propsreturn (
<Container><Component {...pageProps} /></Container>
);
}
}
// PageComponent.jsximportReact, { Component } from'react';
classCodeextendsReact.Component
{
staticasync getInitialProps ({ query, ctx }) {
const decodedResponse = ctx.api.decode(query.code); // Cannot read property 'api' of undefinedreturn {
code: query.code,
decoded: decodedResponse
};
}
render () {
return (
<div>
[...]
</div>
);
}
}
exportdefaultCode;
Does it make sense to you?
Post a Comment for "Accessing Consumed React.context In Next.js Getinitialprops Using Hoc"