Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

setState on empty field in JSON object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "ModifiedBy": "Ciaran Crowley"
}

>Solution :

const handleCreateData = (e) => {
 setDetails((prev) => {
    prev.ModifiedBy = userInfo.name || ''
    return prev;
 });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading