0

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

1
  • What is newValue, an array or an object? If it's an array, is it an array of objects? Commented Sep 24, 2021 at 14:10

1 Answer 1

2

Try this!

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

Here is the documentation for setState

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

Sign up to request clarification or add additional context in comments.

3 Comments

His state is an array.
Wops, updated! :)
Thank you very very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.