Home > OS >  TypeScript/React how to setState type array with type object?
TypeScript/React how to setState type array with type object?

Time:09-11

just recently started learning TypeScript and started to refactor my old React courses. Now following problem I encountered:

import { useState } from "react";

interface User {
  id: string;
  firstName: string;
  email: string;
  age: number;
} 
interface Users {
  user: User;
  users: User[];
}

const MultipleInputs = () => {
  const [user, setUser] = useState({
    firstName: "",
    email: "",
    age: 0,
  });
  const [users, setUsers] = useState<User[]>([]);

  const handleChange = (e: React.ChangeEvent) => {
    const name = (e.target as HTMLInputElement).name;
    const value = (e.target as HTMLInputElement).value;
    setUser({ ...user, [name]: value });
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (user.firstName && user.email && user.age) {
      const newPerson = { ...user, id: new Date().getTime().toString() };
      setUsers([...user, newPerson]); ❌
    }
  };

Error:

ERROR in 2-multiple-inputs.tsx:32:20
TS2461: Type '{ firstName: string; email: string; age: number; }' is not an array type.
    30 |     if (user.firstName && user.email && user.age) {
    31 |       const newPerson = { ...user, id: new Date().getTime().toString() };     
  > 32 |       setUsers([...user, newPerson]);
       |                    ^^^^
    33 |     }
    34 |   };

Did I miss something obvious or is there a different approach?

Thanks in advance.

CodePudding user response:

There is a typo, in line 32 that should be users not user.

 setUsers([...users, newPerson]);

rest looks good, also if you want to push any item at the end of the array, simply use the push() method, no need to use the array restructuring. Like -

users.push(newPerson)
setUsers(users);
  • Related