Skip to content

Commit

Permalink
refactor: auth-forms > useTransition -> useState
Browse files Browse the repository at this point in the history
  • Loading branch information
sadmann7 committed Mar 9, 2024
1 parent d4669dd commit 94b0a62
Show file tree
Hide file tree
Showing 18 changed files with 148 additions and 206 deletions.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,20 @@ const oauthProviders = [
}[]

export function OAuthSignIn() {
const [isLoading, setIsLoading] = React.useState<OAuthStrategy | null>(null)
const [loading, setLoading] = React.useState<OAuthStrategy | null>(null)
const { signIn, isLoaded: signInLoaded } = useSignIn()

async function oauthSignIn(provider: OAuthStrategy) {
if (!signInLoaded) return null
try {
setIsLoading(provider)
setLoading(provider)
await signIn.authenticateWithRedirect({
strategy: provider,
redirectUrl: "/sso-callback",
redirectUrlComplete: "/",
})
} catch (error) {
setIsLoading(null)
setLoading(null)

const unknownError = "Something went wrong, please try again."

Expand All @@ -54,9 +54,9 @@ export function OAuthSignIn() {
variant="outline"
className="w-full bg-background sm:w-auto"
onClick={() => void oauthSignIn(provider.strategy)}
disabled={isLoading !== null}
disabled={loading !== null}
>
{isLoading === provider.strategy ? (
{loading === provider.strategy ? (
<Icons.spinner
className="mr-2 size-4 animate-spin"
aria-hidden="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useForm } from "react-hook-form"
import { toast } from "sonner"
import type { z } from "zod"

import { catchClerkError } from "@/lib/utils"
import { showErrorToast } from "@/lib/handle-error"
import { resetPasswordSchema } from "@/lib/validations/auth"
import { Button } from "@/components/ui/button"
import {
Expand All @@ -28,7 +28,7 @@ type Inputs = z.infer<typeof resetPasswordSchema>
export function ResetPasswordConfirmForm() {
const router = useRouter()
const { isLoaded, signIn, setActive } = useSignIn()
const [isPending, startTransition] = React.useTransition()
const [loading, setLoading] = React.useState(false)

// react-hook-form
const form = useForm<Inputs>({
Expand All @@ -40,40 +40,39 @@ export function ResetPasswordConfirmForm() {
},
})

function onSubmit(data: Inputs) {
async function onSubmit(data: Inputs) {
if (!isLoaded) return

startTransition(async () => {
try {
const attemptFirstFactor = await signIn.attemptFirstFactor({
strategy: "reset_password_email_code",
code: data.code,
password: data.password,
})
setLoading(true)

try {
const attemptFirstFactor = await signIn.attemptFirstFactor({
strategy: "reset_password_email_code",
code: data.code,
password: data.password,
})

if (attemptFirstFactor.status === "needs_second_factor") {
// TODO: implement 2FA (requires clerk pro plan)
} else if (attemptFirstFactor.status === "complete") {
await setActive({
session: attemptFirstFactor.createdSessionId,
})
router.push(`${window.location.origin}/`)
toast.success("Password reset successfully.")
} else {
console.error(attemptFirstFactor)
}
} catch (err) {
catchClerkError(err)
if (attemptFirstFactor.status === "needs_second_factor") {
// TODO: implement 2FA (requires clerk pro plan)
} else if (attemptFirstFactor.status === "complete") {
await setActive({
session: attemptFirstFactor.createdSessionId,
})
router.push(`${window.location.origin}/`)
toast.success("Password reset successfully.")
} else {
console.error(attemptFirstFactor)
}
})
} catch (err) {
showErrorToast(err)
} finally {
setLoading(false)
}
}

return (
<Form {...form}>
<form
className="grid gap-4"
onSubmit={(...args) => void form.handleSubmit(onSubmit)(...args)}
>
<form className="grid gap-4" onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="password"
Expand Down Expand Up @@ -120,8 +119,8 @@ export function ResetPasswordConfirmForm() {
</FormItem>
)}
/>
<Button disabled={isPending}>
{isPending && (
<Button disabled={loading}>
{loading && (
<Icons.spinner
className="mr-2 size-4 animate-spin"
aria-hidden="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useForm } from "react-hook-form"
import { toast } from "sonner"
import type { z } from "zod"

import { catchClerkError } from "@/lib/utils"
import { showErrorToast } from "@/lib/handle-error"
import { checkEmailSchema } from "@/lib/validations/auth"
import { Button } from "@/components/ui/button"
import {
Expand All @@ -27,7 +27,7 @@ type Inputs = z.infer<typeof checkEmailSchema>
export function ResetPasswordForm() {
const router = useRouter()
const { isLoaded, signIn } = useSignIn()
const [isPending, startTransition] = React.useTransition()
const [loading, setLoading] = React.useState(false)

// react-hook-form
const form = useForm<Inputs>({
Expand All @@ -37,34 +37,33 @@ export function ResetPasswordForm() {
},
})

function onSubmit(data: Inputs) {
async function onSubmit(data: Inputs) {
if (!isLoaded) return

startTransition(async () => {
try {
const firstFactor = await signIn.create({
strategy: "reset_password_email_code",
identifier: data.email,
})
setLoading(true)

try {
const firstFactor = await signIn.create({
strategy: "reset_password_email_code",
identifier: data.email,
})

if (firstFactor.status === "needs_first_factor") {
router.push("/signin/reset-password/confirm")
toast.message("Check your email", {
description: "We sent you a 6-digit verification code.",
})
}
} catch (err) {
catchClerkError(err)
if (firstFactor.status === "needs_first_factor") {
router.push("/signin/reset-password/confirm")
toast.message("Check your email", {
description: "We sent you a 6-digit verification code.",
})
}
})
} catch (err) {
showErrorToast(err)
} finally {
setLoading(false)
}
}

return (
<Form {...form}>
<form
className="grid gap-4"
onSubmit={(...args) => void form.handleSubmit(onSubmit)(...args)}
>
<form className="grid gap-4" onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="email"
Expand All @@ -78,8 +77,8 @@ export function ResetPasswordForm() {
</FormItem>
)}
/>
<Button disabled={isPending}>
{isPending && (
<Button disabled={loading}>
{loading && (
<Icons.spinner
className="mr-2 size-4 animate-spin"
aria-hidden="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import type { z } from "zod"

import { catchClerkError } from "@/lib/utils"
import { showErrorToast } from "@/lib/handle-error"
import { authSchema } from "@/lib/validations/auth"
import { Button } from "@/components/ui/button"
import {
Expand All @@ -27,7 +27,7 @@ type Inputs = z.infer<typeof authSchema>
export function SignInForm() {
const router = useRouter()
const { isLoaded, signIn, setActive } = useSignIn()
const [isPending, startTransition] = React.useTransition()
const [loading, setLoading] = React.useState(false)

// react-hook-form
const form = useForm<Inputs>({
Expand All @@ -38,36 +38,35 @@ export function SignInForm() {
},
})

function onSubmit(data: Inputs) {
async function onSubmit(data: Inputs) {
if (!isLoaded) return

startTransition(async () => {
try {
const result = await signIn.create({
identifier: data.email,
password: data.password,
})
setLoading(true)

if (result.status === "complete") {
await setActive({ session: result.createdSessionId })
try {
const result = await signIn.create({
identifier: data.email,
password: data.password,
})

router.push(`${window.location.origin}/`)
} else {
/*Investigate why the login hasn't completed */
console.log(result)
}
} catch (err) {
catchClerkError(err)
if (result.status === "complete") {
await setActive({ session: result.createdSessionId })

router.push(`${window.location.origin}/`)
} else {
/*Investigate why the login hasn't completed */
console.log(result)
}
})
} catch (err) {
showErrorToast(err)
} finally {
setLoading(false)
}
}

return (
<Form {...form}>
<form
className="grid gap-4"
onSubmit={(...args) => void form.handleSubmit(onSubmit)(...args)}
>
<form className="grid gap-4" onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="email"
Expand Down Expand Up @@ -98,8 +97,8 @@ export function SignInForm() {
</FormItem>
)}
/>
<Button type="submit" disabled={isPending}>
{isPending && (
<Button type="submit" disabled={loading}>
{loading && (
<Icons.spinner
className="mr-2 size-4 animate-spin"
aria-hidden="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useForm } from "react-hook-form"
import { toast } from "sonner"
import type { z } from "zod"

import { catchClerkError } from "@/lib/utils"
import { showErrorToast } from "@/lib/handle-error"
import { authSchema } from "@/lib/validations/auth"
import { Button } from "@/components/ui/button"
import {
Expand All @@ -28,7 +28,7 @@ type Inputs = z.infer<typeof authSchema>
export function SignUpForm() {
const router = useRouter()
const { isLoaded, signUp } = useSignUp()
const [isPending, startTransition] = React.useTransition()
const [loading, setLoading] = React.useState(false)

// react-hook-form
const form = useForm<Inputs>({
Expand All @@ -39,37 +39,36 @@ export function SignUpForm() {
},
})

function onSubmit(data: Inputs) {
async function onSubmit(data: Inputs) {
if (!isLoaded) return

startTransition(async () => {
try {
await signUp.create({
emailAddress: data.email,
password: data.password,
})
setLoading(true)

// Send email verification code
await signUp.prepareEmailAddressVerification({
strategy: "email_code",
})
try {
await signUp.create({
emailAddress: data.email,
password: data.password,
})

router.push("/signup/verify-email")
toast.message("Check your email", {
description: "We sent you a 6-digit verification code.",
})
} catch (err) {
catchClerkError(err)
}
})
// Send email verification code
await signUp.prepareEmailAddressVerification({
strategy: "email_code",
})

router.push("/signup/verify-email")
toast.message("Check your email", {
description: "We sent you a 6-digit verification code.",
})
} catch (err) {
showErrorToast(err)
} finally {
setLoading(false)
}
}

return (
<Form {...form}>
<form
className="grid gap-4"
onSubmit={(...args) => void form.handleSubmit(onSubmit)(...args)}
>
<form className="grid gap-4" onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="email"
Expand All @@ -96,8 +95,8 @@ export function SignUpForm() {
</FormItem>
)}
/>
<Button disabled={isPending}>
{isPending && (
<Button disabled={loading}>
{loading && (
<Icons.spinner
className="mr-2 size-4 animate-spin"
aria-hidden="true"
Expand Down
File renamed without changes.
Loading

0 comments on commit 94b0a62

Please sign in to comment.