Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can we access context values inside componentDidMount? #15

Open
razvan-soare opened this issue Nov 10, 2018 · 2 comments
Open

Can we access context values inside componentDidMount? #15

razvan-soare opened this issue Nov 10, 2018 · 2 comments
Labels
enhancement New feature or request

Comments

@razvan-soare
Copy link

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
Copy link
Author

razvan-soare commented Nov 10, 2018

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 fabe added the enhancement New feature or request label Nov 14, 2018
@fabe
Copy link
Owner

fabe commented Nov 14, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants