I there! I'm using typescript in my React project. Now I want to create a useState of array of objects but I have a important error when I want to add a new record. How Can add a new value to my useState? Thanks!
// interfaces.type.ts
export interface ManagementDocuments {
id: number;
idDocument: number;
name: string;
// shippers.tsx
const [shipperManagementDocumentsSelected, setShipperManagementDocumentsSelected] = useState<ManagementDocuments[]>([]);
const inputChangeHandler = (name, newValue): any => {
switch (name) {
case DocumentType.MANAGEMENT:
// the problem starts here, I don't know how to add a new record to my useState
setShipperManagementDocumentsSelected(
...shipperManagementDocuments,
newValue
);
.
.
.
}
}
CodePudding user response:
Try this!
setShipperManagementDocumentsSelected(prev => {
return [
...prev,
newValue
]
);
Here is the documentation for setState