Currently trying to render a list of components that expands/shrinks as values are added/removed from an array of a custom object type. However, whenever I make the called to push a value into a new array and then pass that into a hook, the array simply replaces the previous value rather than making the list of objects longer. Any help appreciated.
// My interface
interface IAddedSkill {
id: string,
level: Level,
name: string,
}
const [potentialSkills, setPotentialSkills] = useState<IAddedSkill[]>([]);
let addedSkills: IAddedSkill[] = [];
function handleAddedSkills(addedSkill: IAddedSkill) {
addedSkills.push(addedSkill);
setPotentialSkills(addedSkills);
}
...some code in between
// Rendering the react component using this hook
{potentialSkills.map(skill => (
<Chip label={skill.name} onDelete={() => handleDelete(skill)} />
))}
Can anyone see something I'm doing wrong that would cause this behaviour?
Edit: Thanks for all the answers, the implementation I used that resolved the issue was changing the handleAddSkills function to:
function handleAddedSkills(addedSkill: IAddedSkill) {
setPotentialSkills([...potentialSkills, addedSkill]);
}
I also completely removed any reference to the addedSkills list and removed the declaration.