1

Syntax Error: Invalid left-hand side in assignment expression

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.

Submitted May 27th 2021 by Admin

Answers
0

Optional chaining should be used when reading the value, not when assigning it. You can update the piece of code to this:

if (student?.grade != null) { student.grade = grade;
}

Admin | 3 months ago



Relevant Questions