Created
September 19, 2019 14:19
-
-
Save wrburgess/e874a5b7eb5190a25c370f21a2382a0c to your computer and use it in GitHub Desktop.
React useState with single object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { useState } = React; | |
function signupUser() { | |
return new Promise(resolve => { | |
setTimeout(resolve, 1000); | |
}); | |
} | |
const initialState = { | |
username: "", | |
email: "", | |
password: "", | |
passwordConfirmation: "" | |
}; | |
const Signup = () => { | |
const [ | |
{ username, email, password, passwordConfirmation }, | |
setState | |
] = useState(initialState); | |
const clearState = () => { | |
setState({ ...initialState }); | |
}; | |
const onChange = e => { | |
const { name, value } = e.target; | |
setState(prevState => ({ ...prevState, [name]: value })); | |
}; | |
const handleSubmit = e => { | |
e.preventDefault(); | |
signupUser().then(clearState); | |
}; | |
return ( | |
<form onSubmit={handleSubmit}> | |
<div> | |
<label> | |
Username: | |
<input value={username} name="username" onChange={onChange} /> | |
</label> | |
</div> | |
<div> | |
<label> | |
Email: | |
<input value={email} name="email" onChange={onChange} /> | |
</label> | |
</div> | |
<div> | |
<label> | |
Password: | |
<input | |
value={password} | |
name="password" | |
type="password" | |
onChange={onChange} | |
/> | |
</label> | |
</div> | |
<div> | |
<label> | |
Confirm Password: | |
<input | |
value={passwordConfirmation} | |
name="passwordConfirmation" | |
type="password" | |
onChange={onChange} | |
/> | |
</label> | |
</div> | |
<button>Submit</button> | |
</form> | |
); | |
}; | |
ReactDOM.render(<Signup />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment