Mitch Tal
Mitch Tal

Reputation: 49

Adding an element to an existing array in react hooks

So I have this state variable:

const [Class, setClass] = useState({ Teacher: "John Fartsalot", Year: 2021, Students: [] });

and I have a:

ver studentObject

I want to push the studentObject into the Students array dynamically using setClass.

I came across this post: Push method in React Hooks (useState)? but it seems to be relevant only when there's just the list in there.

What is the correct way to do so in my case?

Upvotes: 1

Views: 10497

Answers (2)

Jay Singh
Jay Singh

Reputation: 206

This is correct way to add:

setStudents(students => [...students, studentObject]);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370769

While you could spread the existing Class into a new object, and then spread the new students array into that new object as well, it would be better to follow the convention and separate out the state variables (as React recommends), and to not use Class as a variable name (it's very close to the reserved word class). Consider:

const [teacher, setTeacher] = useState('John Fartsalot');
const [year, setYear] = useState(2021);
const [students, setStudents] = useState([]);

Then to add to the students array, do

setStudents([...students, studentObject]);

Or, if students happens to be in a stale closure at this point, then

setStudents(students => [...students, studentObject]);

Upvotes: 4

Related Questions