[SOLVED] Pass useState type

Issue

I have a simple app like this

import React, { useState } from 'react'
import AddToList from './components/AddToList'
import List from './components/List'

export interface IProps{
  name: string
  age: number
  url: string
  note: string
}

const App = () => {

  const[people, setPeople] = useState([{
    name: 'chris',
    url: '',
    age: 21,
    note: 'note note'
  }])

  return (
    <div>
      <h2>People Invited</h2>
      <List people={people}/>
      <AddToList people setPeople/>
    </div>
  )
}

export default App

Just a simple useState with one object and an interface.

I have a List component to show the objects in people.

I want to have a form in AddToList to add to people.

I’m passing people and setPeople to AddToList

import React from 'react'
import {IProps as Props} from '../App'

interface IProps{
    people: Props[]
    setPeople:any
}

const AddToList:React.FC<IProps> = ({people, setPeople}) => {
  return (
    <div>AddToList</div>
  )
}

export default AddToList    

In the app <AddToList people setPeople/> people here is erroring beacuse of the type of people here in AddToList

interface IProps{
    people: Props[]
    setPeople:any
}

what should the type be here people: Props[]

Solution

<MyComponent foo />

Is actually just shorthand for:

<MyComponent foo={true} />

It does not mean:

<MyComponent foo={foo} />

If you want to pass in those props you either need:

<AddToList people={people} setPeople={setPeople} /> 

Or you can spread them as an object:

<AddToList {...{ people, setPeople }} />

Also the correct type for a react state setter function is:

Dispatch<SetStateAction<T>>

Where T is the type of your state. In that case that would be:

interface IProps{
    people: Props[]
    setPeople: Dispatch<SetStateAction<Props[]>>
}

Answered By – Alex Wayne

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *