Skip to content

Commit

Permalink
chore: proper fetching and using sonner toast
Browse files Browse the repository at this point in the history
  • Loading branch information
shawakash committed Mar 10, 2024
1 parent ab809c2 commit 82f2977
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 60 deletions.
44 changes: 26 additions & 18 deletions apps/web/app/signup/components/otp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,17 @@ import {
InputOTPSlot,
InputOTPSeparator,
} from "@/components/ui/input-otp"
import { toast } from "@/components/ui/use-toast"
import React from "react"
import { AccountType, BACKEND_URL, OtpValid, responseStatus } from "@paybox/common"
import { useSession } from "next-auth/react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"


export function OTPForm() {

const router = useRouter()
const session = useSession();
console.log(session, "session")
const form = useForm<z.infer<typeof OtpValid>>({
resolver: zodResolver(OtpValid),
defaultValues: {
Expand All @@ -38,22 +39,29 @@ export function OTPForm() {
})

const onSubmit = async (data: z.infer<typeof OtpValid>) => {
const { status, msg, valid, walletId, account }: { status: responseStatus, msg: string, valid?: boolean, walletId?: string, account?: AccountType } =
await fetch(`${BACKEND_URL}/client/valid?otp=${data.otp}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
//@ts-ignore
"Authorization": `Bearer ${session.data?.user?.jwt}`
},
}).then((res) => res.json());
console.log(status, "valid")
toast({
title: "Otp Validation Status",
description: (
<h1>{msg}</h1>
),
})
toast.promise(
fetch(`${BACKEND_URL}/client/valid?otp=${data.otp}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
//@ts-ignore
"Authorization": `Bearer ${session.data?.user?.jwt}`
},
}).then((res) => res.json()), {
loading: "Validating OTP",
success: async ({ status, msg, valid, walletId, account }) => {
// TODO: Add the walletId to the session
if (status === responseStatus.Ok) {
session.update()
router.push("/profile")
return msg;
}
return msg;
},
error: ({status, msg}) => {
return msg;
}
});
}

return (
Expand Down
120 changes: 78 additions & 42 deletions apps/web/app/signup/components/resendOtp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,59 +27,100 @@ import { Label } from "@/components/ui/label"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { toast } from "@/components/ui/use-toast"
import { BACKEND_URL, ResendOtpValid } from "@paybox/common";
import { useSession } from "next-auth/react"
import React from "react"
import { toast } from "sonner"


export function ResendOtp() {

// USE THE ATOM TO GET THE USER'S EMAIL, PHONE NUMBER and JWT
// CALL THE API TO RESEND THE OTP
const session = useSession();

const formRef = React.useRef<HTMLFormElement>(null)
const form = useForm<z.infer<typeof ResendOtpValid>>({
resolver: zodResolver(ResendOtpValid),
defaultValues: {
email: "",
email: session.data?.user?.email ?? "",
//@ts-ignore
mobile: (session.data?.user?.mobile || "").toString() ?? "",
//@ts-ignore
name: session.data?.user?.firstname ?? ""
},
})

const onSubmit = async (data: z.infer<typeof ResendOtpValid>) => {
toast({
title: "Resending Otp..",
description: (
<h1>Resending Otp to {data.email}, {data.mobile}</h1>
),
})
const { status, msg }: {status: string, msg: string} =
await fetch(`${BACKEND_URL}/client/resend?mobile=${data.mobile}&email=${data.email}&name=Akash`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
}).then((res) => res.json());
// handle the response
toast({
title: `Resending Otp..`,
description: (
<h1>{status}: {msg}</h1>
),
})
console.log("here")
const call = async () => {
try {
const { status, msg }: { status: string, msg: string } =
await fetch(`${BACKEND_URL}/client/resend?mobile=${data.mobile}&email=${data.email}&name=Akash`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
//@ts-ignore
"Authorization": `Bearer ${session.data?.user?.jwt}`
},
}).then((res) => res.json());
return {status, msg}
} catch (error) {
throw new Error("Error in sending otp")
return {error}
}
}
toast.promise(call(), {
loading: "Re-Sending otp...",
success: ({status, msg}) => {
return msg;
},
error: ({e}) => {
console.error(e);
return `Error in sending otp: ${e.message}`;
},
});
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<Dialog>
<DialogTrigger asChild>
<Button variant="link">Resend Otp</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<Dialog>
<DialogTrigger asChild>
<Button variant="link">Resend Otp</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<DialogHeader>
<DialogTitle>Resend Otp</DialogTitle>
<DialogDescription>
Re-check your email or phone for the OTP to send.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col space-y-3 pt-2">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel className="" htmlFor="mobile">
Name
</FormLabel>
<FormControl>
<div className="flex items-center space-x-2">
<div className="grid flex-1 gap-2">
<Input
id="name"
type="text"
//@ts-ignore
placeholder={`${session.data?.user?.firstname}`}
autoComplete="firstname"
autoCorrect="off"
{...field}
/>
</div>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="mobile"
Expand All @@ -94,6 +135,8 @@ export function ResendOtp() {
<Input
id="mobile"
type="text"
//@ts-ignore
placeholder={`${session.data?.user?.mobile}`}
autoComplete="mobile"
autoCorrect="off"
{...field}
Expand All @@ -119,6 +162,7 @@ export function ResendOtp() {
<Input
id="email"
type="text"
placeholder={`${session.data?.user?.email}`}
autoComplete="email"
autoCorrect="off"
{...field}
Expand All @@ -134,24 +178,16 @@ export function ResendOtp() {
<DialogFooter className="w-full">
<DialogClose asChild>
<div className="w-full flex justify-between">
<Button
type="submit"
// onSubmit={() => setIsLoading(true)}
>
{/* {isLoading && (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
)} */}
Send Otp
</Button>
<Button type="submit">Send Otp</Button>
<Button type="button" variant="secondary">
Close
</Button>
</div>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog >
</form>
</form>
</DialogContent>
</Dialog >
</Form>

)
Expand Down

0 comments on commit 82f2977

Please sign in to comment.