fabe/gatsby-universal

Can we access context values inside componentDidMount?

razvan-soare opened this issue · 2 comments

Hey im trying to pass my context to all my pages.

I saw that is possible to have it in render like:
return ( <Consumer> {props => <h1> WOW </h1>} </Consumer> )

But im not really sure how to get it inside the componentDidMount or any other methods. I tried to look for it inside this.context or this.props.context but no luck..

Any ideas ?
Thank you

Ok little update.. i managed to do something using a higher order function like this

const withContext = Component => {
  return class Wrapper extends React.PureComponent {
    render() {
      return (
        <Consumer>
          {store => {
            return <Component {...this.props} store={store} />;
          }}
        </Consumer>
      );
    }
  };
};

And when exporting my components i just do export default withContext(Component)
Not sure if this is the best solution :-?? but would love to hear an opinion.

Thank you

fabe commented

@razvan-soare Hey, what you could also try is to play with the wrapRootElement or wrapPageElement functions inside gatsby-browser.js—and wrapping the <Consumer> there.

However, an HOC seems like a good addition for this purpose. Feel free to submit a PR (adding this function to /src/store), otherwise I'll take care of this in the next couple days. Thanks!