Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying an array received from Usestate hook with Typescript

I am trying to display an array of information using map that is received from the usestate hook. When writing the map function, I get a "Cannot invoke an expression whose type lacks a call signature." Error. If I create a function that returns the same information and call that function, I do not get the error.

    export default function Portfolio() {
      const [portfolioData, setPortfoloioData] = useState<IProject[] | []>([])

      useEffect(() => {
        const portfolio: IProject[] = getPortfolio()
        setPortfoloioData(portfolio)
      }, [])

//Function to display the map that works.
      const displayBlocks = (portfolioData: IProject[]): JSX.Element[] => {
        return portfolioData.map((item, index) =>
          <ProjectBlock key={index} project={item} index={index} />
        )
      }

      return (
        <div className='text-center pt-3'>
          <h1 className='pb-4'>Portfolio</h1>

//This works without error
          {displayBlocks(portfolioData)} 

//This shows the missing call signature error even though
//it is the same as what is returned by the displayBlocks function.
          {portfolioData.map((item, index) =>
            <ProjectBlock key={index} project={item} index={index} />
          )}
        </div>
      )
    }

I would like to figure out how to display the information with a simple map within the return section without having to call another function. What am I doing wrong?

like image 423
Brian Gwaltney Avatar asked Jul 07 '19 02:07

Brian Gwaltney


People also ask

How do you define an array in useState TypeScript?

To type the useState hook as an array of objects in React, use the hook's generic, e.g. const [employees, setEmployees] = useState<{salary: number; name: string}[]>([]) . The state variable can be initialized to an empty array and will only accept objects of the specified type. Copied!

How do I use TypeScript in useState?

To type the useState hook as an object in React, use the hook's generic, e.g. const [employee, setEmployee] = useState<{name: string; salary: number}>({name: '',salary: 0}) . The state variable will only accept key-value pairs of the specified type.

What is the output of useState () hook?

Output: The value returned by useState() consists of an array with two values. The first value is the initial (or starting) value of the state variable, while the second value is a reference to the function that can be used to update the variable.


1 Answers

You error is this line

const [portfolioData, setPortfoloioData] = useState<IProject[] | []>([]);

portfolioData become union type of IProject[] | []. In this case it is useless and leads to error. Any variable of type IProject[] can hold empty array. So it is no need to create union of array of type IProject and array of type any (square braces without type are considered of type any).

To correct errors just do

const [portfolioData, setPortfoloioData] = useState<IProject[]>([]);

And if you want to dig into details why this happens, I recommend to read this (it best describes the issue) and this.

like image 76
Fyodor Avatar answered Sep 28 '22 10:09

Fyodor