I have an array with Persons and want to spread new entries. But I do not have Persons to spread, just lastNames. How do I solve this?
type Person = {
name: string,
lastName: string,
age: number
}
function MyComponent() {
const [persons, setPersons] = useState<Person[]>([])
function addNewPersons(lastName: string[]): void {
setPersons((prevState: Person[]) => [
...prevState,
// spread lastName[] onto Person[]
]);
}
return <></>;
}
CodePudding user response:
Possibly something like this...
type Person = {
name?: string;
lastName: string;
age?: number;
};
function MyComponent() {
const [persons, setPersons] = useState<Person[]>([]);
function addNewPersons(lastNames: string[]) {
const newPersons: Person[] = lastNames.map((lastName) => ({
lastName,
}));
setPersons((prevPersons: Person[]) => [...prevPersons, ...newPersons]);
}
return <></>;
}