Issue
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 <></>;
}
Solution
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 <></>;
}
Answered By - cefn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.