Jennifer
Jennifer

Reputation: 343

Why typescript throw error at useState react

I'm stuck at figuring out why TS throw me bunch of error although I already supplied interface to my initialState for one of my state.

can anyone help with my code below?

interface initialStateProps {
  eventInfo: {
    name: string;
    location: string;
  }
}

class Dashboard extends Component<RouteComponentProps> {
  //what is wrong here? ts showing bunch of error?
  const [formValues, setFormValues] = useState<initialStateProps>({
    eventInfo: {
      name: '',
      location: ''
    }
  })

  return <div></div>

}

Upvotes: 0

Views: 414

Answers (1)

wentjun
wentjun

Reputation: 42536

It seems like you are trying to use React Functional Components, as you are using the useState hook.

In that case, you should not be creating a class and extending it from React.Component, as those are for defining class components.

This is how you can define functional components using React and TypeScript.

interface initialStateProps {
  eventInfo: {
    name: string; 
    location: string;
  }
}

const Dashboard: React.FC = () => {
  const [formValues, setFormValues] = useState<initialStateProps>({
    eventInfo: {
      name: '',
      location: ''
    }
  })

  return <div></div>

};

Upvotes: 2

Related Questions