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

How to add and update json array elements using react hooks

I defined a state with null array, Then that array will contain firstname, lastname etc..based on entry in text field. I need to add the prop if not present and update the prop if present. I need to do validation in save based on that. I tried with below code, but that not works.

const [signerData, setSignerData] = useState([]);

const newItems = [...signerData];
newItems["firstName"] = inputValue;
setSignerData({ newItems });

Any help is appreciated. Thank you.

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

>Solution :

Firstly, you would need an object instead of an array. Array doesn’t allow you to have keys, only values. The below code would work.

const [signerData, setSignerData] = useState({});

setSignerData({ ...signerData, firstName: inputValue });
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