I have a list of people, each with an id. I have to add a tag to a newly created array for a person with a certain id. The json object 'students' already exists and I am updating it using its useState setStudents method but it seems to be returning an unidentified object back. My plan was as follows:
const updateStudent = (tag, id) => {
setStudents((prevStudents) => {
prevStudents.map((student) => {
if (student.id !== id) return student;
if (student.tags) {
student["tags"].push(tag);
} else {
student["tags"] = [tag];
}
return student;
});
});
};
Sorry if my explanation was confusing but tldr: I'm just trying to add an item to an array of a specified object and it doesn't seem to be working.
A "cleaner" approach would be something like this:
const updateStudent = (tag, id) => {
// form a new students object
let newStudents = students.map(student => {
if(student.id === id) {
student.tags? student.tags.push(tag) : student.tags = [tag];
}
return student;
});
setStudents(newStudents); // set the newly formed object to state
}
It is better to separate the update logic from setting the state