Issue
I have a Main.tsx file where i have a Record ,personList,with key as PersonId and value as PersonInfo,i want to delete a particular entry from personList,based on Id provided.Below is my code:
interface PersonInfo{
FirstName:string;
SecondName:string;
Age:string;
}
const [personList,setPersonList] = useState<Record<string,PersonInfo>>({});
//For inserting entry
const Create = () => {
setPersonList((oldList)=>{
return {
...oldList,[PersonId]:PersonDescription //PersonDescription is of type PersonInfo
}
});
};
const Delete = () => {
const newPersonList :Record<string,PersonInfo>=
personList.filter()//Here i want to delete the entry based on personId
setPersonList(newPersonList);
};
Solution
Since you're already assigning the keys of your object to the personId
you can just do:
const Delete = (id: string): void => {
const filteredPersonList: Record<string,PersonInfo> = {}
for(let key in personList){
if(key !== id){
filteredPersonList[key] = personList[key]
}
}
setPersonList(filteredPersonList)
}
Answered By - ehutchllew
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.