Home > Back-end >  setState on empty field in JSON object
setState on empty field in JSON object

Time:06-10

I have the empty field ModifiedBy. I need to populate it with a username stored in session storage, userInfo.name.

const [details, setDetails] = useState("");

const handleCreateData = (e) => {
    setDetails((prev) => {
        return { ...prev, ModifiedBy: userInfo.name };
    });
}

This method only works when ModifiedBy is already populated in data. I need to be able to populate ModifiedBy when it is empty, and update it is populated.

A quick example of my JSON

{
  "ModifiedBy": "Ciaran Crowley"
}

CodePudding user response:

const handleCreateData = (e) => {
 setDetails((prev) => {
    prev.ModifiedBy = userInfo.name || ''
    return prev;
 });
}
  • Related