-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Advanced: Form state management step 2 – useLoginForm #11
Draft
lucasconstantino
wants to merge
6
commits into
lessons/08-react-apis
Choose a base branch
from
lessons/08-react-apis--part-2
base: lessons/08-react-apis
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
1925403
feat: added mapObject util
lucasconstantino d53abb1
fix: removed tempory animation inducer on input component
lucasconstantino 40bd123
feat: added input inline error message
lucasconstantino 28f7794
feat: added initial login form state
lucasconstantino f3b6c92
feat: added useLoginForm state manager
lucasconstantino 3193deb
feat: updated LoginPage to use useLoginForm hook
lucasconstantino File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
import type { ChangeEvent, FocusEvent, FormEvent } from 'react' | ||
import { useCallback, useMemo, useState } from 'react' | ||
|
||
import { mapObject } from '~/utils/mapObject' | ||
|
||
type TFields = 'email' | 'password' | ||
type TValues = { [key in TFields]: string } | ||
type TValidator = <TValue>(value: TValue) => void | string | ||
|
||
const initials = { | ||
values: { | ||
email: '', | ||
password: '', | ||
}, | ||
|
||
touched: { | ||
email: false, | ||
password: false, | ||
}, | ||
} | ||
|
||
const validators: { [key in TFields]: TValidator } = { | ||
email: (value) => { | ||
if (typeof value !== 'string') return 'Invalid e-mail value type' | ||
if (!value) return 'E-mail is required' | ||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(value)) return 'Invalid e-mail' | ||
}, | ||
|
||
password: (value) => { | ||
if (typeof value !== 'string') return 'Invalid password value type' | ||
if (!value) return 'Password is required' | ||
}, | ||
} | ||
|
||
/** | ||
* Controls login form state. | ||
*/ | ||
const useLoginForm = () => { | ||
const [values, setValues] = useState<TValues>(initials.values) | ||
const [touched, setTouched] = useState(initials.touched) | ||
const [isSubmitting, setIsSubmitting] = useState(false) | ||
const [submitError, setSubmitError] = useState<Error | null>(null) | ||
|
||
// Compute errors based on validators. | ||
const errors = useMemo( | ||
() => mapObject(validators, (fn, field) => fn(values[field]) ?? null), | ||
[values] | ||
) | ||
|
||
// Compute the validity of field. | ||
const invalid = useMemo(() => mapObject(errors, Boolean), [errors]) | ||
|
||
// Form is invalid when any field is invalid. | ||
const isValid = useMemo( | ||
() => !Object.values(invalid).some(Boolean), | ||
[invalid] | ||
) | ||
|
||
/** | ||
* Form submit handler constructor. | ||
*/ | ||
const handleSubmit = useCallback( | ||
(handler: (values: TValues) => Promise<void | Error>) => | ||
(e: FormEvent<HTMLFormElement>) => { | ||
e.preventDefault() | ||
|
||
// Touch all fields uppon submission trial, so that | ||
// errors might be shown to the UI. | ||
setTouched((touched) => mapObject(touched, () => true)) | ||
|
||
if (isValid) { | ||
setIsSubmitting(true) | ||
|
||
const handling = handler(values) | ||
|
||
handling | ||
.catch(setSubmitError) | ||
// Ensure we reset submit state even if promise fails | ||
.finally(() => setIsSubmitting(false)) | ||
} | ||
}, | ||
[values, isValid] | ||
) | ||
|
||
/** | ||
* Input value change handler. | ||
*/ | ||
const handleChange = useCallback((e: ChangeEvent<HTMLInputElement>) => { | ||
const { name, value } = e.target | ||
|
||
// Update value. | ||
setValues((values) => ({ ...values, [name]: value })) | ||
}, []) | ||
|
||
/** | ||
* Input value blur handler. | ||
*/ | ||
const handleBlur = useCallback((e: FocusEvent<HTMLInputElement>) => { | ||
const { name } = e.target | ||
|
||
setTouched((touched) => ({ ...touched, [name]: true })) | ||
}, []) | ||
|
||
return { | ||
values, | ||
touched, | ||
errors, | ||
invalid, | ||
isValid, | ||
isSubmitting, | ||
submitError, | ||
handleSubmit, | ||
handleChange, | ||
handleBlur, | ||
} as const | ||
} | ||
|
||
export { useLoginForm } |
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/** | ||
* Maps through an object's properties. | ||
* | ||
* i.e.: | ||
* mapObject({ foo: '' }, (value, key) => key) // { foo: 'foo' } | ||
* mapObject({ foo: 1, bar: 3 }, (value) => value + 1) // { foo: 2, bar; 4 } | ||
*/ | ||
const mapObject = < | ||
TObject extends object, | ||
TKeys extends keyof TObject, | ||
TResult | ||
>( | ||
obj: TObject, | ||
fn: (value: TObject[keyof TObject], key: TKeys, obj: TObject) => TResult | ||
) => | ||
Object.fromEntries( | ||
Object.entries(obj).map(([key, value]) => [ | ||
key, | ||
fn(value, key as TKeys, obj), | ||
]) | ||
) as { [key in TKeys]: TResult } | ||
|
||
export { mapObject } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not gonna pretend I understand all the type syntax used, but it's nice to what potentially Formik or ReactHooks are doing under the hood.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Completely agree. Until this point I was pretty confident whats going on in our project, but this one seems more like an expert approach. Nice showcase.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@OndrejDrapalik @matyasmihalka this definitely isn't the most straight-forward code. In fact, this is why we decided it wasn't necessary to include as our "main track" in the application.
The idea here is really to showcase how libraries such as Formik are made, and how complex proper form state handling can be without those libraries.
I'll give you a hint though: React Hook Forms is way, waaay more complex than Formik, as it takes over React entirely, building it's solution on top of traps and Proxy states, executing hooks dynamically based on state consumption. Quite neat. If you are interested, we could have a chat about it or explore a simpler isolated solution to showcase the technique.