gatsby-universal icon indicating copy to clipboard operation
gatsby-universal copied to clipboard

Can we access context values inside componentDidMount?

Open razvan-soare opened this issue 6 years ago • 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

razvan-soare avatar Nov 10 '18 10:11 razvan-soare

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

razvan-soare avatar Nov 10 '18 15:11 razvan-soare

@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!

fabe avatar Nov 14 '18 17:11 fabe