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?

2 Answers 2

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

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 }))
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)
1

This is correct way to add:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.