1

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?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Mitch Tal
  • 49
  • 1
  • 8

2 Answers2

4

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]);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you, this approach seems to work but unfortunately I may need to alter an existing student list later on from the database. Is there a way to insert it directly? I will change the name of the Class state either way. Something like this maybe? setClassData(ClassData => ({ ...ClassData, Students: *some-code* })) – Mitch Tal Jan 05 '21 at 16:32
  • You should really separate out the separate types of state into different state variables. If you get a new student list from the DB, just call `setStudents` with it. `setStudents(studentsFromDB)` – CertainPerformance Jan 05 '21 at 16:36
1

This is correct way to add:

setStudents(students => [...students, studentObject]);
vvvvv
  • 25,404
  • 19
  • 49
  • 81
Jay Singh
  • 181
  • 2
  • 6