Skip to content

Instantly share code, notes, and snippets.

@alonbardavid
Created October 9, 2019 17:48
Show Gist options
  • Save alonbardavid/07bd96802a4befb1b06a377823e805dd to your computer and use it in GitHub Desktop.
Save alonbardavid/07bd96802a4befb1b06a377823e805dd to your computer and use it in GitHub Desktop.
Why use mobx gist9
class Form {
@observable
email = ""
@observable
password = ""
@computed
get emailError(){
if (this.email && this.email.length >0 &&
this.email.indexOf("@") >= 0){
return "email must contain @ character"
}
return null
}
@computed
get passwordError(){
if (this.password && this.password.length >0 &&
this.password.length < 8){
return "password must have 8 characters"
}
return null
}
@computed
get valid(){
return this.email && !this.emailError &&
this.password && !this.passwordError
}
@action
setEmail(event){
this.email = event.target.value;
}
@action
setPassword(event){
this.password=event.target.value;
}
}
return function FormView(props){
const {submitForm} = props;
const form = useMemo(()=>new Form(),[true]);
return <form onSubmit={()=>form.valid && submitForm(form)}>
<input name="email" value={form.email}
onChange={form.setEmail} />
{form.emailError && <div>{form.emailError}</div>}
<input name="password" value={form.password}
onChange={form.setPassword} type="password"/>
{form.passwordError && <div>{form.passwordError}</div>}
</form>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment