I have the following class-based component. And I had to convert it to a functional component
import React from 'react' import { API } from '../../api' import { JobPosting } from '../../types' import { JobPostings } from './JobPostings' interface State { jobPostings: JobPosting[] loading: boolean } export class JobPostingsPage extends React.Component<{}, State> { state = { jobPostings: [], loading: true, } componentDidMount() { API.jobPostings.loadAll().then(({ data }) => { this.setState({ jobPostings: data, loading: false, }) }) } render() { if (this.state.loading) { return null } return ( <div> <h1>Job Postings</h1> <JobPostings jobPostings={this.state.jobPostings} /> </div> ) } }
Now, I want to convert above class based to functional component. So I used useState and useEffect and converted it to functional based as below
import React, { useState, useEffect } from 'react' import { API } from '../../api' import { jobPostings } from '../../api/jobPostings' import { JobPosting } from '../../types' import { JobPostings } from './JobPostings' interface State { jobPostings: JobPosting[] loading: boolean } export const JobPostingsPage: React.FC<State> = ({} ) => { const [jobPostings, setJobPostings] = useState<JobPosting[]>([]); const [loading, setLoading] = useState(true); useEffect(() => { API.jobPostings.loadAll().then(({ data }) => { setJobPostings(data); setLoading(false) }) }) return( loading ? null: ( <div> <h1>Job Postings</h1> <JobPostings jobPostings={jobPostings} /> </div> ) )}
The problem I face is that it is giving an error when I do npm start. It says
Type '{}' is missing the following properties from type 'State': jobPostings, loading TS2739
This points to the below code in router file
const routes = { home: '/', } export const Router: React.FC = () => ( <BrowserRouter> <Switch> <Route exact path={routes.home}> <JobPostingsPage /> -------------------> ERROR ON THIS LINE <------------ </Route> </Switch> </BrowserRouter> )
Any idea where I am going wrong with the conversion. Please any input is appreciated.
Advertisement
Answer
The problem is in this line:
export const JobPostingsPage: React.FC<State> = ({} ) => {
Here should be the props
defined instead of the state. From the class component I take that the props are empty, so you should exchange it for this and be fine:
export const JobPostingsPage: React.FC<{}> = ({} ) => {