Overview
useRequestForgotPasswordCodeByEmail hook is used to handle the process of requesting a forgot password code via email.
It leverages the react-query library to manage the asynchronous operation and provides error handling and success callbacks.
useRequestForgotPasswordCodeByEmail is responsible only for requesting code.
You need to implement a useUpdateUserPasswordWithCode that handles password updating process.
Example Usage
request-code-component.tsx
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { HttpError } from '@locai1/iam-javascript';
import { useRequestForgotPasswordCodeByEmail } from '@locai1/iam-react';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
const formSchema = z.object({
email: z.string().min(1),
});
type FormSchemaType = z.infer<typeof formSchema>;
type RequestCodeFormProps = {
onComplete: (email: string) => void;
onSignInClick: () => void;
email?: string;
};
export const RequestCodeComponent = ({ onComplete, email = '' }: RequestCodeFormProps) => {
const [error, setError] = useState<HttpError | Error>();
const resetPasswordUrl = typeof window !== 'undefined' ?
`${window.location.origin}/forgot-password?code={{code}}` :
`/forgot-password?code={{code}}`;
const form = useForm<FormSchemaType>({
resolver: zodResolver(formSchema),
defaultValues: {
email,
},
});
const { requestResetCodeByEmail } = useRequestForgotPasswordCodeByEmail({
onError: setError,
onSuccess: () => {
onComplete(form.getValues().email);
},
resetPasswordUrl,
});
const handleSubmit = form.handleSubmit(async (values: FormSchemaType) => {
setError(undefined);
requestResetCodeByEmail(values.email);
});
return (
<Form {...form}>
<form onSubmit={handleSubmit}>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>E-mail</FormLabel>
<FormControl>
<Input type="email" placeholder="[email protected]" required {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{error?.message}
<Button type="submit">Continue</Button>
</form>
</Form>
);
};
Parameters
callback function that is called when the request process is successful.
onError
HttpErrorCallback
required
callback function that is called when an error occurs during the request process.type HttpErrorCallback = (error: HttpError | Error | undefined) => void;
Reset password url used to redirect user to reset password page from email.
It should contain a placeholder for the reset password code.
Returns
function that triggers the request process with the provided email
boolean indicating whether the request process is currently in progress.
boolean indicating whether an error occurred during the request process.
error object if an error occurred during the request process.