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

SSR: this.context is undefined #218

Closed
Vanuan opened this Issue Sep 19, 2016 · 1 comment

Comments

Projects
None yet
1 participant
@Vanuan
Copy link
Contributor

Vanuan commented Sep 19, 2016

Suppose you have the following react component,
and you want to render it using getDataFromTree.

class MyComponent extends React.Component {
  constructor(props) {
    super(props); // <-- context parameter is ignored
  }

  componentWillMount() {
    this.context.something; // <-- Cannot read property 'something' of undefined error
  }
}

Cannot read property 'something' of undefined error occurs.

It appears that this code:

https://github.com/apollostack/react-apollo/blob/4271f68d604e7a6f9c23c7a123a0b15573cafd0e/src/server.ts#L48

const Component = new ComponentClass(ownProps, context);

Doesn't set context if it isn't used in constructor (for some reason it does in the browser).

I didn't check React's source code, but it looks like it sets context even if it isn't used in constructor.

Here's a suggested fix:

    const Component = new ComponentClass(ownProps, context);
    try {
      Component.props = ownProps;
+      Component.context = context; // not sure about this
      Component.setState = (newState: any) => {
        Component.state = assign({}, Component.state, newState);
      };
    } catch (e) {} // tslint:disable-line
@Vanuan

This comment has been minimized.

Copy link
Contributor Author

Vanuan commented Sep 19, 2016

Here's a documentation about context: https://facebook.github.io/react/docs/context.html

Vanuan added a commit to Vanuan/react-apollo that referenced this issue Sep 19, 2016

@Vanuan Vanuan referenced this issue Sep 19, 2016

Merged

Fix #218 #219

jbaxleyiii pushed a commit that referenced this issue Sep 19, 2016

Fix #218 (#219)
Fix #218
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment