Skip to content

Injection fails inside the constructor of React components #1

Open
@ghost

Description

I wish I could give this project more stars, because it has saved me a lot of time and made my code much cleaner. Thanks for the awesome library!

There's one issue I'm having, though. I'm trying to use a dependency inside the constructor of a React component, and somehow the library always complains with the following error:

Error: Provider is not found.
  Please define Provider and set Loader.contextType = InjectorContext e.g.
  @provider([MyService, MyService])
  class App extends React.Component { /*...*/ }
  class Loader extends React.Component {
    static contextType = InjectorContext;
  }

I've set up everything in accordance with the documentation (I think).

@provider([Session, toClass(Session)])
class App extends React.Component {
  render() {
    if (this.state.loading) {
      return <Loader />
    }
    // ...
  }
}

class Loader extends React.Component {

  @inject session: Session
  
  constructor(props) {
    super(props)
    this.session.doSomethingUseful()  
  }
  
  render() {
    // ...
  }

  static contextType = InjectContext

}

Is there something I'm missing, or is this use case currently not supported by the library? Everything works fine if I defer accessing the dependency in <Loader /> to componentDidMount, so I'm guessing this is either a bug or a limitation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions