Home > database >  Pass useState type
Pass useState type

Time:03-17

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[]

CodePudding user response:

<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[]>>
}

CodePudding user response:

I changed the line from
<AddToList people setPeople/>
To
<AddToList people={people} setPeople={setPeople}/> and it worked for me. The error typescript was throwing for me was that type "boolean" was not assignable to type Props[]. So when I did a assign like this it worked, however it may vary depending on your typescript version.

  • Related