29er
29er

Reputation: 9005

Need help solving a React Typescript error

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!

Upvotes: 0

Views: 2904

Answers (1)

basarat
basarat

Reputation: 276171

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.

Upvotes: 4

Related Questions