I am trying to implement a simple optional chaining state update. What I want is for the items to ONLY be changed IF the item is defined/exists; if not/is undefined, I want the item to keep the previous state (e.g userID should remain = 2 if not updated).
To test this out I created an object with three variables:
const userObj = {
firstName: "",
lastName: "",
userID: 2,
};
Then I created a function to update state:
const updateState = (item) => {
return {
userObj.firstName = item?.firstName,
userObj.lastName = item?.lastName,
userObj.userID = item?.userID,
};
};
Finally I pass the item which contains only one item to update (firstName) and I call the function:
const item = {
firstName: "None",
};
console.log(updateState(item));
The output:
userObj.firstName = item?.firstName,
^
SyntaxError: Unexpected token '.'
But when I hover over userObj
I can see its properties: