Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

SSR: this.context is undefined #218

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

SSR: this.context is undefined #218

Vanuan opened this issue Sep 19, 2016 · 1 comment

Comments

@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
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 mentioned this issue Sep 19, 2016
jbaxleyiii pushed a commit that referenced this issue Sep 19, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant