Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useState empty array type

interface Crumb {
  title: string;
  url: string;
}
interface Crumbies {
  crumbsArray: Crumb[];
}


// component
const [breadcrumbs, setBreadcrumbs] = useState<Crumbies>([]);

I'm getting an error:

TS2345: Argument of type 'never[]' is not assignable to parameter of type 'Crumbies | (() => Crumbies)'.   Type 'never[]' is not assignable to type '() => Crumbies'.     Type 'never[]' provides no match for the signature '(): Crumbies'.

How to provide a correct typings for an empty array in useState hook?

UPDATE 1

const Breadcrumbs: React.FC<Crumbies> = ({ crumbsArray }) => {}

That's why i've created another interface Crumbies to wrap Crumb. Is there a better approach to this?

like image 249
Alexander Kim Avatar asked Feb 22 '20 07:02

Alexander Kim


People also ask

How to use usestate hook as array of objects in react?

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 to manage an array in React state variable?

useState Hook in React. Let’s take a simple example to manage an array in the state variable. 1. Create a react application First, we’ll create a simple react application to implement the demo using create-react-app npm package. Run the following command to create a startup application.

How to type the usestate hook with an empty object initial value?

To type the useState hook with an empty object initial value in React, use the hook's generic, e.g. const [employee, setEmployee] = useState< { [key: string]: any}> ( {}). The state variable will be typed as an object with dynamic properties and values.

How to initialize the state variable with an empty array?

The state variable can be initialized to an empty array and will only accept objects of the specified type. Copied! We used a generic to type the useState hook correctly while initializing the hook with an empty array.


1 Answers

The interface called Crumbies requires you to pass an object with a field crumbsArray:

const [breadcrumbs, setBreadcrumbs] = useState<Crumbies>({crumbsArray: []});

If you want to simply have an array of Crumb you don't need to create a new interface, you can simply do it in useState:

const [breadcrumbs, setBreadcrumbs] = useState<Crumb[]>([]);

This will initialise it with an empty array.

like image 145
tudor.gergely Avatar answered Oct 17 '22 10:10

tudor.gergely