I have received data from backend which contains a student object.
The student contains a field named grade. I would like to explicitly update that value of the student object in my code:
// the component parses the student object, I don't show those code here
useEffect(() => {
const {grade} = calculateNewGrade(student);
// Syntax Error: Invalid left-hand side in assignment expression
student?.grade = grade;
}, [student]);
When I run my app, I ended up with error "Invalid left-hand side in assignment expression" for the code showed above. Why? What is the correct way to update that value then?
=== About using the optional syntax student?.grade ===
The reason why I use optional syntax is that the student at the beginning is undefined or null until it is loaded. If I remove the optional ? I would end up with another error "undefined is not an object" when evaluating student.grade.
Optional chaining should be used when reading the value, not when assigning it. You can update the piece of code to this:
if (student != null) {
student.grade = grade;
}
Edit: Mistake pointed out by Felix King
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With