Created
November 1, 2024 02:01
-
-
Save Jacob-Roberts/4023a410e1a728343c79e3f676591a20 to your computer and use it in GitHub Desktop.
Toast Notifications with React Server Actions
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
"use server"; | |
export async function signInWithEmail(_: any, formData: FormData) { | |
// Sign in | |
return { | |
errors: null, | |
}; | |
} |
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
"use client"; | |
import Form from "next/form"; | |
import { useActionState } from "react"; | |
import { LoadingSpinner } from "#components/loading-spinner.tsx"; | |
import { Button } from "#components/ui/button.tsx"; | |
import { Input } from "#components/ui/input.tsx"; | |
import { Label } from "#components/ui/label.tsx"; | |
import { signInWithEmail } from "./actions.ts"; | |
import { toast } from "sonner"; | |
async function submitSignInWithEmail(prev: any, formData: FormData) { | |
const res = await signInWithEmail(prev, formData); | |
toast.success("Check your email", { | |
description: "We sent you a login link. Be sure to check your spam too.", | |
}); | |
return res; | |
} | |
export function SignInWithEmail() { | |
const [state, submitAction, isPending] = useActionState( | |
submitSignInWithEmail, | |
{ | |
errors: null, | |
}, | |
); | |
const { errors } = state; | |
return ( | |
<Form action={submitAction}> | |
<div className="grid gap-2"> | |
<div className="grid gap-1"> | |
<Label className="sr-only" htmlFor="email"> | |
</Label> | |
<Input | |
id="email" | |
name="email" | |
placeholder="name@example.com" | |
type="email" | |
autoCapitalize="none" | |
autoComplete="username" | |
autoCorrect="off" | |
className="dark:text-white" | |
required | |
disabled={isPending} | |
/> | |
{errors?.email && ( | |
<p className="px-1 text-xs text-red-600">{errors.email}</p> | |
)} | |
</div> | |
<Button type="submit" disabled={isPending}> | |
{isPending && <LoadingSpinner className="mr-2 h-4 w-4" />} | |
Sign In with Email | |
</Button> | |
</div> | |
</Form> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment