Property 'state' does not exist on type 'FetchPeriod'

Dylan picture Dylan · Jun 28, 2018 · Viewed 7.6k times · Source

I'm trying to learn ReactJS following this tutorial: Tutorial

I'm new to the programming language so i'm clueless as to what to do now.

When I try to add the "Fetchemployee.tsx" file, I get an error at the this.state method.

(TS) Property 'state' does not exist on type 'FetchPeriod'

This is the code:

import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { Link, NavLink } from 'react-router-dom';

interface FetchPeriodDataState {
    periodList: PeriodData[];
    loading: boolean;
}

export class FetchPeriod extends React.Component<RouteComponentProps<{}>, FetchPeriodDataState> {
    constructor(props) {
        super(props);
    this.state = { periodList: [], loading: true };


    fetch('api/Period/Index')
        .then(response => response.json() as Promise<PeriodData[]>)
        .then(data => {
            this.setState({ periodList: data, loading: false });
        });

    // This binding is necessary to make "this" work in the callback  
    this.handleDelete = this.handleDelete.bind(this);
    this.handleEdit = this.handleEdit.bind(this);
}

And then later on I have the PeriodData class:

export class PeriodData {
PeriodId: number = 0;
Description: string = "";
PeriodOwner: string = "";
PeriodName: string = "";}

The this.state and this.setState methods are giving the errors in the title, and I can't seem to find a fix.

Answer

Roman picture Roman · Mar 15, 2019

One of possible causes of the problem is missing the React type definitions Therefore you can try to install them:

npm install --save-dev @types/react @types/react-dom

Without the types installed, TS can't properly infer the props needed for JSX elements.