Search code examples
reactjsreact-hooksuse-statearray-pushreact-typescript

How to push nested object interface array in React Typescript using useState


Interface

  interface ListInterface {
    listName: string;
    list: string[];
  }

useState

  const [initialList, setinitialList] = useState<ListInterface>({listName: "List1", list:['One', 'Two', 'Three', 'Four', 'Five', 'Six']});
  const [selectedList, setSelectedList] = useState<ListInterface>(initialList);

I know how to add new elements (push) to array. But having trouble when the array is in object/inteface. How do you do it with useState hooks?

setTheArray(oldArray => [...oldArray, newElement]);

I have created a simple sandbox example.

  • Use the input field to add a new text to array selectedList.list

https://codesandbox.io/s/reacr-ts-nested-object-array-example-z1uyd?file=/src/App.tsx


Solution

  • You have defined an object interface, so that means that you need to push an object that conforms to that type each time you want to update it.

      
      // ...
    
      const [text, setText] = useState<string>(''); // <--- set type and set to blank to remove type errors due to `text` being possibly undefined
    
      // ...
    
      const handleSubmit = (event: any) => {    
        event.preventDefault();
        console.log("Submitted: " + text);
    
        //setSelectedList({list: oldArray => [...oldArray, newElement]});
        // the above wont work because it is an array, but `ListInterface` is an object (you might want to change the name to `ListEntry` or `ListObject` to avoid confusion)
    
        setSelectedList({
          listName: selectedList.listName,
          list: [...selectedList.list, text]
        })
    
      };
    

    Appreciate the accept. Check out @axtck's answer as well, as they make a few other important improvements to your code!