import type { FormEvent } from 'react'; import { useId, useState } from 'react'; import { httpPost } from '../../lib/http'; import { COURSE_PURCHASE_PARAM, FIRST_LOGIN_PARAM, setAuthToken } from '../../lib/jwt'; type EmailLoginFormProps = { isDisabled?: boolean; setIsDisabled?: (isDisabled: boolean) => void; }; export function EmailLoginForm(props: EmailLoginFormProps) { const { isDisabled, setIsDisabled } = props; const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const [isLoading, setIsLoading] = useState(false); const handleFormSubmit = async (e: FormEvent) => { e.preventDefault(); setIsLoading(true); setIsDisabled?.(true); setError(''); const { response, error } = await httpPost<{ token: string; isNewUser: boolean; }>(`${import.meta.env.PUBLIC_API_URL}/v1-login`, { email, password, }); // Log the user in and reload the page if (response?.token) { setAuthToken(response.token); const currentLocation = window.location.href; const url = new URL(currentLocation, window.location.origin); url.searchParams.set(FIRST_LOGIN_PARAM, response?.isNewUser ? '1' : '0'); url.searchParams.set(COURSE_PURCHASE_PARAM, '1'); window.location.href = url.toString(); return; } // @todo use proper types if ((error as any).type === 'user_not_verified') { window.location.href = `/verification-pending?email=${encodeURIComponent( email, )}`; return; } setIsLoading(false); setIsDisabled?.(false); setError(error?.message || 'Something went wrong. Please try again later.'); }; const emailFieldId = `form:${useId()}`; const passwordFieldId = `form:${useId()}`; return (
setEmail(String((e.target as any).value))} /> setPassword(String((e.target as any).value))} />

Reset your password?

{error && (

{error}

)}
); }