0

I am trying to convert a non-TS React component to using Typescript. In this component I am getting this error:

Class 'Component' defines instance member function 'componentWillMount', but extended class 'Root' defines it as instance member property.

Here is my component:

import * as React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import { Provider } from "react-redux";


import createStore from "./state";
import { getCurrentUser } from "./util";
import { setValidUser } from "./state/actions/auth-actions";
const { store } = createStore();

class Root extends React.Component<any> {

  componentWillMount = async () => {
    const currentUser = await getCurrentUser();

    if (currentUser) {
      store.dispatch(setValidUser(currentUser));
    }
  }

  render() {
    return (
      <Provider store={store}>
          <Router>
            {this.props.children}
          </Router>
      </Provider>
    );
  }
}

export default (Component, props = {}) => {
  render(
    <Root>
      <Component {...props} />
    </Root>,
    document.getElementById("root"),
  );
};

I am not a pro at TS yet, obvioulsy, and not sure how to resolve this. thanks!

2
  • 1
    What are you doing by this -> import * as React from "react";? it should be import React from "react"; Commented Feb 19, 2018 at 16:57
  • using @types/react, you must use import * as React from "react", otherwise you will get 'has no default export' errors. Commented Feb 19, 2018 at 17:28

1 Answer 1

4

Class 'Component' defines instance member function 'componentWillMount', but extended class 'Root' defines it as instance member property.

Change your property:

componentWillMount = async () => {

to a member function:

async componentWillMount() {

These names come from OO concepts

More

I would even:

 componentWillMount() {
    this.asyncMount();
 }

 asyncMount = async () => {
    const currentUser = await getCurrentUser();

    if (currentUser) {
      store.dispatch(setValidUser(currentUser));
    }
  }

As React will not wait for your componentWillMount to wait and its async nature might confuse your fellow developers.

Sign up to request clarification or add additional context in comments.

3 Comments

Can you take some time to explain the differences between these two syntaxes?
One is a class with a function and the other is a class with a variable that is a function.
Thanks so much for clarifying this!. Yep it fixed the errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.