Search code examples
reactjstypescriptreact-typescript

React Typescript How to add a new array to an array of objects useState


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

        );
        .
        .
        .
    }
}

enter image description here


Solution

  • Try this!

    setShipperManagementDocumentsSelected(prev => {
       return [ 
          ...prev,
          newValue
       ]
    );
    

    Here is the documentation for setState

    https://reactjs.org/docs/hooks-reference.html#usestate