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

React-NextJs – pass data from input attribute & input value as key:value json to state

i’m trying to set user registration state from a function that runs from every single input in a form, and the function receives 2 parameters.. key & value
the key is equal to the input name attribute and the value is equal to the input value..

when i run this function the parameters that the function receives are correct but when i use the key:value in a setState the key remains "key" and the value passes correctly..

here’s the code.

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

    const [userRegister, setUserRegister] = useState(
            {
                "userFirstName":"", 
                "userLastName":"", 
                "userEmail":"", 
                "userPhoneNumber":"", 
                "userPassword":""
            }
        );

    function handleValidation(key, value) {
        console.log(key);
        console.log(value);
        setUserRegister({...userRegister , key:value})
    }
                        <input 
                        type="text" 
                        name="userFirstName" 
                        id="userFirstName" 
                        placeholder="first name"
                        onBlur={(e) => handleValidation(e.target.name, e.target.value)}
                        />

Thanks 🙂

>Solution :

In order to replace the value of a varible as an object’s key, use [].
Example:
setUserRegister({...userRegister , [key]:value})

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