diff --git a/src/app/api/health/route.js b/src/app/api/health/route.ts
similarity index 100%
rename from src/app/api/health/route.js
rename to src/app/api/health/route.ts
diff --git a/src/app/api/ofertas/route.js b/src/app/api/ofertas/route.ts
similarity index 100%
rename from src/app/api/ofertas/route.js
rename to src/app/api/ofertas/route.ts
diff --git a/src/app/api/solicitudes/route.js b/src/app/api/solicitudes/route.ts
similarity index 91%
rename from src/app/api/solicitudes/route.js
rename to src/app/api/solicitudes/route.ts
index be9591fa..1636fc06 100644
--- a/src/app/api/solicitudes/route.js
+++ b/src/app/api/solicitudes/route.ts
@@ -1,4 +1,4 @@
-import { NextResponse } from 'next/server';
+import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
export async function GET() {
@@ -16,7 +16,7 @@ export async function GET() {
return Response.json({ registeredPost });
}
-export async function POST(request) {
+export async function POST(request: NextRequest) {
try {
// Obtener los datos del formulario (multipart/form-data)
const formData = await request.formData();
diff --git a/src/app/api/user/route.js b/src/app/api/user/route.ts
similarity index 100%
rename from src/app/api/user/route.js
rename to src/app/api/user/route.ts
diff --git a/src/app/auth/page.js b/src/app/auth/page.tsx
similarity index 100%
rename from src/app/auth/page.js
rename to src/app/auth/page.tsx
diff --git a/src/app/casos-activos/ofertas/page.js b/src/app/casos-activos/ofertas/page.js
index c2a78d1b..007cfcf3 100644
--- a/src/app/casos-activos/ofertas/page.js
+++ b/src/app/casos-activos/ofertas/page.js
@@ -141,7 +141,7 @@ export default function Ofertas() {
) : (
- data.map((caso) => )
+ data.map((caso) => )
)}
diff --git a/src/app/oferta/page.js b/src/app/oferta/page.js
deleted file mode 100644
index 9007f44f..00000000
--- a/src/app/oferta/page.js
+++ /dev/null
@@ -1,21 +0,0 @@
-import { ArrowLeft } from 'lucide-react';
-import Link from 'next/link';
-
-export default function Oferta() {
- return (
-
-
-
-
No se encontró la oferta.
-
-
- );
-}
diff --git a/src/app/oferta/[id]/page.js b/src/app/ofertas/[id]/page.tsx
similarity index 67%
rename from src/app/oferta/[id]/page.js
rename to src/app/ofertas/[id]/page.tsx
index 80de85ca..a3bbd571 100644
--- a/src/app/oferta/[id]/page.js
+++ b/src/app/ofertas/[id]/page.tsx
@@ -1,37 +1,31 @@
'use client';
-import { useEffect, useState } from 'react';
+
import { useParams } from 'next/navigation';
-import { supabase } from '@/lib/supabase/client';
import { ArrowLeft } from 'lucide-react';
import OfferCard from '@/components/OfferCard';
-import { useTowns } from '@/context/TownProvider';
+import { useQuery } from '@tanstack/react-query';
+import { HelpRequestData } from '@/types/Requests';
+import { helpRequestService } from '@/lib/service';
export default function CasoDetalle() {
const params = useParams();
const { id } = params;
- const [caso, setCaso] = useState(null);
- const [loading, setLoading] = useState(true);
- const { towns } = useTowns();
- useEffect(() => {
- async function fetchCaso() {
- const { data, error } = await supabase.from('help_requests').select('*').eq('id', id).single();
- if (error) {
- console.error('Error fetching caso:', error);
- } else {
- setCaso(data);
- }
- setLoading(false);
- }
- fetchCaso();
- }, [id]);
- if (loading) {
+ const {
+ data: request,
+ isLoading,
+ error,
+ } = useQuery
({
+ queryKey: ['help_requests', { id: id }],
+ queryFn: () => helpRequestService.getOne(Number(id)),
+ });
+ if (isLoading) {
return (
);
}
- if (!caso) {
+ if (error || request === undefined) {
return (
@@ -60,7 +54,7 @@ export default function CasoDetalle() {
Volver
-
+
);
}
diff --git a/src/app/ofertas/editar/[id]/page.js b/src/app/ofertas/editar/[id]/page.js
deleted file mode 100644
index c2401786..00000000
--- a/src/app/ofertas/editar/[id]/page.js
+++ /dev/null
@@ -1,40 +0,0 @@
-import { createClient } from '@/lib/supabase/server';
-import OfferHelp from '@/components/OfferHelp';
-import Unauthorized from '@/components/Unauthorized';
-
-const getRequest = async (id) => {
- const supabase = await createClient();
- const { data: session, sessionError } = await supabase.auth.getUser();
- if (sessionError || !session?.user) {
- return 'unauthorized';
- }
- const { data, error } = await supabase
- .from('help_requests')
- .select('*')
- .eq('id', id)
- .eq('type', 'ofrece')
- .contains('additional_info', { email: session.user.email })
- .single();
- if (error) {
- throw new Error(error);
- }
- return data;
-};
-
-export default async function EditarSolicitud({ params }) {
- const { id } = await params;
- const request = await getRequest(id);
- if (request === 'unauthorized') {
- return ;
- }
- return (
-
- );
-}
diff --git a/src/app/ofertas/editar/[id]/page.tsx b/src/app/ofertas/editar/[id]/page.tsx
new file mode 100644
index 00000000..57c438af
--- /dev/null
+++ b/src/app/ofertas/editar/[id]/page.tsx
@@ -0,0 +1,25 @@
+import OfferHelp from '@/components/OfferHelp';
+import Unauthorized from '@/components/Unauthorized';
+import { createClient } from '@/lib/supabase/server';
+import { helpRequestService } from '@/lib/service';
+
+export default async function EditarSolicitud({ params }: { params: Promise<{ id: string }> }) {
+ const { id } = await params;
+ const supabase = await createClient();
+ const { data: session } = await supabase.auth.getUser();
+ if (session.user === null) {
+ return ;
+ }
+ const numberId = Number(id);
+ const request = await helpRequestService.getOne(numberId);
+ return (
+
+ );
+}
diff --git a/src/app/ofertas/page.js b/src/app/ofertas/page.tsx
similarity index 87%
rename from src/app/ofertas/page.js
rename to src/app/ofertas/page.tsx
index a3fac973..38c01f7e 100644
--- a/src/app/ofertas/page.js
+++ b/src/app/ofertas/page.tsx
@@ -10,6 +10,7 @@ import { useTowns } from '@/context/TownProvider';
import { useSession } from '@/context/SessionProvider';
import OfferCard from '@/components/OfferCard';
import Link from 'next/link';
+import { HelpRequestData } from '@/types/Requests';
export default function ListaSolicitudes() {
const session = useSession();
@@ -17,20 +18,20 @@ export default function ListaSolicitudes() {
const searchParams = useSearchParams();
const router = useRouter();
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
- const [data, setData] = useState([]);
- const [currentPage, setCurrentPage] = useState(Number(searchParams.get('page')) || 1);
- const [currentCount, setCurrentCount] = useState(0);
+ const [data, setData] = useState([]);
+ const [currentPage, setCurrentPage] = useState(Number(searchParams.get('page')) || 1);
+ const [currentCount, setCurrentCount] = useState(0);
const { towns } = useTowns();
const itemsPerPage = 10;
- const numPages = (count) => {
+ const numPages = (count: number) => {
return Math.ceil(count / itemsPerPage) || 0;
};
- const updateFilter = (filter, value) => {
+ const updateFilter = (filter: 'urgencia' | 'tipoAyuda' | 'pueblo' | 'page', value: string) => {
const params = new URLSearchParams(searchParams.toString());
params.set(filter, value);
router.push(`?${params.toString()}`);
@@ -41,7 +42,7 @@ export default function ListaSolicitudes() {
pueblo: searchParams.get('pueblo') || 'todos',
});
- const changeDataFilter = (type, newFilter) => {
+ const changeDataFilter = (type: 'urgencia' | 'tipoAyuda' | 'pueblo', newFilter: string) => {
setFiltroData((prev) => ({
...prev,
[type]: newFilter,
@@ -49,9 +50,9 @@ export default function ListaSolicitudes() {
updateFilter(type, newFilter);
};
- function changePage(newPage) {
+ function changePage(newPage: number) {
setCurrentPage(newPage);
- updateFilter('page', newPage);
+ updateFilter('page', newPage.toString());
}
useEffect(() => {
async function fetchData() {
@@ -64,7 +65,7 @@ export default function ListaSolicitudes() {
.from('help_requests')
.select('*', { count: 'exact' })
.eq('type', 'ofrece')
- .contains('additional_info', { email: session.user.email });
+ .contains('additional_info', { email: session.user?.email });
// Solo agregar filtro si no es "todos"
if (filtroData.pueblo !== 'todos') {
query.eq('town_id', filtroData.pueblo);
@@ -80,7 +81,7 @@ export default function ListaSolicitudes() {
.range((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage - 1)
.order('created_at', { ascending: false });
- if (error) {
+ if (error || count === null) {
console.log('Error fetching solicitudes:', error);
setData([]);
} else {
@@ -174,16 +175,7 @@ export default function ListaSolicitudes() {
) : (
- data.map((caso) => (
-
diff --git a/src/app/ofrecer-ayuda/page.js b/src/app/ofrecer-ayuda/page.tsx
similarity index 100%
rename from src/app/ofrecer-ayuda/page.js
rename to src/app/ofrecer-ayuda/page.tsx
diff --git a/src/app/personas-animales-desaparecidos/page.js b/src/app/personas-animales-desaparecidos/page.tsx
similarity index 98%
rename from src/app/personas-animales-desaparecidos/page.js
rename to src/app/personas-animales-desaparecidos/page.tsx
index d309ee4e..f2adeb18 100644
--- a/src/app/personas-animales-desaparecidos/page.js
+++ b/src/app/personas-animales-desaparecidos/page.tsx
@@ -1,4 +1,4 @@
-// personas-animales-desaparecidos/page.js
+// personas-animales-desaparecidos/page.tsx
import { Users, PawPrint, Car, UserSearch } from 'lucide-react';
diff --git a/src/app/personas-desaparecidas/page.js b/src/app/personas-desaparecidas/page.js
deleted file mode 100644
index f972f404..00000000
--- a/src/app/personas-desaparecidas/page.js
+++ /dev/null
@@ -1,346 +0,0 @@
-'use client';
-
-import { useState } from 'react';
-import { UserSearch, AlertCircle, Phone, Check } from 'lucide-react';
-import { supabase } from '@/lib/supabase/client';
-
-export default function PersonaDesaparecida() {
- const [formData, setFormData] = useState({
- // Datos personales
- nombreCompleto: '',
- edad: '',
- genero: '',
- altura: '',
- complexion: '',
-
- // Descripción física
- descripcionFisica: '',
- ropa: '',
-
- // Último avistamiento
- lugarUltimaVez: '',
- fechaUltimaVez: '',
- horaUltimaVez: '',
- circunstancias: '',
-
- // Información médica
- condicionesMedicas: '',
-
- // Datos del reportante
- nombreReportante: '',
- parentesco: '',
- telefonoContacto: '',
- telefonoAlternativo: '',
-
- consentimiento: false,
- });
-
- const [status, setStatus] = useState({
- isSubmitting: false,
- error: null,
- success: false,
- });
-
- // En el handleSubmit, reemplazar con:
-
- const handleSubmit = async (e) => {
- e.preventDefault();
-
- if (!formData.consentimiento) {
- alert('Debe aceptar el consentimiento para enviar el reporte');
- return;
- }
-
- setStatus({ isSubmitting: true, error: null, success: false });
-
- try {
- // Preparar datos para Supabase
- const missingPersonData = {
- name: formData.nombreCompleto,
- age: parseInt(formData.edad),
- gender: formData.genero,
- height: formData.altura ? parseInt(formData.altura) : null,
- description: formData.descripcionFisica,
- last_seen_location: formData.lugarUltimaVez,
- last_seen_date: new Date(`${formData.fechaUltimaVez}T${formData.horaUltimaVez}`).toISOString(),
- reporter_name: formData.nombreReportante,
- reporter_contact: formData.telefonoContacto,
- status: 'active',
- medical_conditions: formData.condicionesMedicas || null,
- clothing_description: formData.ropa,
- additional_info: {
- circumstances: formData.circunstancias,
- secondary_contact: formData.telefonoAlternativo,
- relationship: formData.parentesco,
- },
- };
-
- // Insertar directamente usando supabase
- const { error } = await supabase.from('missing_persons').insert([missingPersonData]);
-
- if (error) throw error;
-
- // Limpiar formulario
- setFormData({
- nombreCompleto: '',
- edad: '',
- genero: '',
- altura: '',
- complexion: '',
- descripcionFisica: '',
- ropa: '',
- lugarUltimaVez: '',
- fechaUltimaVez: '',
- horaUltimaVez: '',
- circunstancias: '',
- condicionesMedicas: '',
- nombreReportante: '',
- parentesco: '',
- telefonoContacto: '',
- telefonoAlternativo: '',
- consentimiento: false,
- });
-
- setStatus({ isSubmitting: false, error: null, success: true });
- setTimeout(() => setStatus((prev) => ({ ...prev, success: false })), 5000);
- } catch (error) {
- console.error('Error al enviar el reporte:', error);
- setStatus({
- isSubmitting: false,
- error: 'Error al enviar el reporte. Por favor, inténtalo de nuevo.',
- success: false,
- });
- }
- };
-
- return (
-
- {/* Banner de emergencia 112 */}
-
-
-
-
-
-
- LLAME PRIMERO AL 112
-
-
- Si la desaparición es reciente o sospecha que la persona está en peligro inmediato, contacte primero con
- el 112.
-
-
-
-
-
- {status.error && (
-
- )}
-
- {/* Formulario principal */}
-
-
-
-
Reportar Persona Desaparecida
-
-
-
-
-
- {status.success && (
-
-
-
-
-
El reporte ha sido enviado correctamente.
-
- Gracias por proporcionar esta información. Las autoridades han sido notificadas.
-
-
-
-
- )}
-
- );
-}
diff --git a/src/app/solicitar-ayuda/page.js b/src/app/solicitar-ayuda/page.tsx
similarity index 100%
rename from src/app/solicitar-ayuda/page.js
rename to src/app/solicitar-ayuda/page.tsx
diff --git a/src/app/solicitudes/editar/[id]/page.tsx b/src/app/solicitudes/editar/[id]/page.tsx
index 58c5d879..d5d4fc0e 100644
--- a/src/app/solicitudes/editar/[id]/page.tsx
+++ b/src/app/solicitudes/editar/[id]/page.tsx
@@ -1,10 +1,9 @@
-import { PageProps } from '.next/types/app/page';
import RequestHelp from '@/components/RequestHelp';
import Unauthorized from '@/components/Unauthorized';
import { helpRequestService } from '@/lib/service';
import { createClient } from '@/lib/supabase/server';
-export default async function EditarSolicitud({ params }: PageProps) {
+export default async function EditarSolicitud({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const supabase = await createClient();
const { data: session } = await supabase.auth.getUser();
diff --git a/src/components/OfferCard.js b/src/components/OfferCard.tsx
similarity index 87%
rename from src/components/OfferCard.js
rename to src/components/OfferCard.tsx
index b58cf373..8aea9f25 100644
--- a/src/components/OfferCard.js
+++ b/src/components/OfferCard.tsx
@@ -1,17 +1,15 @@
-import { Calendar, Heart, HeartHandshake, MapPin, MapPinned, Megaphone, Phone, Truck, User, Users } from 'lucide-react';
-import { useSession } from '../context/SessionProvider';
+import { HeartHandshake, MapPinned, Megaphone, Phone, Truck } from 'lucide-react';
import { tiposAyudaOptions } from '@/helpers/constants';
import Link from 'next/link';
-import PhoneInfo from './PhoneInfo';
+import { HelpRequestData } from '@/types/Requests';
+import { useTowns } from '@/context/TownProvider';
-export default function OfferCard({
- caso,
- isHref,
- towns,
- button = { text: 'Ver oferta', link: '/oferta/' },
- isEdit = false,
-}) {
- const session = useSession();
+type OfferCardProps = {
+ caso: HelpRequestData;
+ showLink?: boolean;
+};
+export default function OfferCard({ caso, showLink = true }: OfferCardProps) {
+ const { towns } = useTowns();
return (
@@ -68,8 +66,7 @@ export default function OfferCard({
- Contacto:{' '}
- {typeof caso.contact_info === 'string' ? caso.contact_info : JSON.parse(caso.contact_info).phone}
+ Contacto: {caso.contact_info}
)}
@@ -130,19 +127,19 @@ export default function OfferCard({
{caso.name || 'Necesita Ayuda'}
- {new Date(caso.created_at).toLocaleDateString() +
+ {new Date(caso.created_at!).toLocaleDateString() +
' ' +
- new Date(caso.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
+ new Date(caso.created_at!).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
- {isHref && (
+ {showLink && (
- {button.text}
+ Ver oferta
)}
diff --git a/src/components/OfferHelp.js b/src/components/OfferHelp.js
index ac321a58..524b4495 100644
--- a/src/components/OfferHelp.js
+++ b/src/components/OfferHelp.js
@@ -14,13 +14,13 @@ import { useRouter } from 'next/navigation';
import { useSession } from '@/context/SessionProvider';
export default function OfferHelp({
- town,
- onClose,
- isModal,
+ town = undefined,
+ onClose = undefined,
+ isModal = false,
data = {},
title = '',
button = ['Registrar oferta de ayuda', 'Enviando oferta...'],
- id,
+ id = 0,
redirect = '/casos-activos/ofertas',
submitType = 'create',
}) {
diff --git a/src/components/Pagination.js b/src/components/Pagination.tsx
similarity index 91%
rename from src/components/Pagination.js
rename to src/components/Pagination.tsx
index f3dfa0a4..5603aa7b 100644
--- a/src/components/Pagination.js
+++ b/src/components/Pagination.tsx
@@ -1,6 +1,11 @@
import React from 'react';
-const Pagination = ({ currentPage, totalPages, onPageChange }) => {
+type PaginationProps = {
+ currentPage: number;
+ totalPages: number;
+ onPageChange: (currentPage: number) => void;
+};
+const Pagination = ({ currentPage, totalPages, onPageChange }: PaginationProps) => {
const getPageNumbers = () => {
const pageNumbers = [];
const rangeSize = 1; // Número de páginas a mostrar alrededor de la actual
diff --git a/src/components/PhoneInfo.js b/src/components/PhoneInfo.tsx
similarity index 83%
rename from src/components/PhoneInfo.js
rename to src/components/PhoneInfo.tsx
index 62d4deef..7d37b487 100644
--- a/src/components/PhoneInfo.js
+++ b/src/components/PhoneInfo.tsx
@@ -1,8 +1,12 @@
import { useQuery } from '@tanstack/react-query';
import { helpRequestService } from '@/lib/service';
import { useSession } from '@/context/SessionProvider';
+import { HelpRequestData } from '@/types/Requests';
-export default function PhoneInfo({ caseInfo }) {
+type PhoneInfoProps = {
+ caseInfo: HelpRequestData;
+};
+export default function PhoneInfo({ caseInfo }: PhoneInfoProps) {
const session = useSession();
const {
diff --git a/src/components/SolicitudCard.tsx b/src/components/SolicitudCard.tsx
index 9d2db443..f1c55ff5 100644
--- a/src/components/SolicitudCard.tsx
+++ b/src/components/SolicitudCard.tsx
@@ -5,7 +5,7 @@ import { useSession } from '@/context/SessionProvider';
import { HelpRequestAdditionalInfo, HelpRequestData } from '@/types/Requests';
import AsignarSolicitudButton from '@/components/AsignarSolicitudButton';
import SolicitudHelpCount from '@/components/SolicitudHelpCount';
-import PhoneInfo from '@/components/PhoneInfo.js';
+import PhoneInfo from '@/components/PhoneInfo';
import { useTowns } from '@/context/TownProvider';
type SolicitudCardProps = {
diff --git a/src/components/Tab.js b/src/components/Tab.tsx
similarity index 64%
rename from src/components/Tab.js
rename to src/components/Tab.tsx
index 88e5e9c4..1e89b338 100644
--- a/src/components/Tab.js
+++ b/src/components/Tab.tsx
@@ -1,8 +1,15 @@
'use client';
import Link from 'next/link';
+import { PropsWithChildren } from 'react';
-export default function Tab({ children, ...props }) {
+type Props = {
+ color: 'red' | 'green' | 'orange';
+ isPath: boolean;
+ href: string;
+};
+
+export default function Tab({ children, ...props }: PropsWithChildren
) {
return (
void;
+};
+
+type Status = {
+ isSubmitting: boolean;
+ error: string | null;
+ success: boolean;
+};
+
+type FormData = {
+ email: string;
+ password: string;
+ privacyPolicy: string;
+};
+
+export default function Login({ onSuccessCallback }: LoginProps) {
+ const [isSignUp, setIsSignUp] = useState(false);
+ const [formData, setFormData] = useState({
email: '',
password: '',
privacyPolicy: '',
});
- const [status, setStatus] = useState({
+ const [status, setStatus] = useState({
isSubmitting: false,
error: null,
success: false,
});
- const [isPrivacyAccepted, setPrivacyAccepted] = useState(true);
+ const [isPrivacyAccepted, setPrivacyAccepted] = useState(true);
- /**
- * Updates privacy policy of user
- * @param {boolean} value
- */
- const updatePrivacyPolicy = async (value) => {
+ const updatePrivacyPolicy = async (value: string) => {
const { data: session, error: errorGettingUser } = await authService.getSessionUser();
if (!session.user || errorGettingUser) {
@@ -47,17 +59,22 @@ export default function Login({ onSuccessCallback }) {
if (!session.user || errorGettingUser) {
throw new Error('Error a la hora de obtener el usuario');
}
- return session.user.user_metadata.privacyPolicy;
+ return session.user.user_metadata.privacyPolicy as string;
};
- const handleSubmit = async (e) => {
+ const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
setStatus({ isSubmitting: true, error: null, success: false });
if (!isPrivacyAccepted) {
if (!formData.privacyPolicy) {
- setError('Para continuar, debes aceptar la Política de Privacidad.');
+ setStatus((prev) => {
+ return {
+ ...prev,
+ error: 'Para continuar, debes aceptar la Política de Privacidad.',
+ };
+ });
return;
}
}
@@ -75,7 +92,7 @@ export default function Login({ onSuccessCallback }) {
}
if (formData.privacyPolicy && !isPrivacyAccepted) {
- await updatePrivacyPolicy(true);
+ await updatePrivacyPolicy('true');
setPrivacyAccepted(true);
}
@@ -132,7 +149,7 @@ export default function Login({ onSuccessCallback }) {
setFormData({ ...formData, privacyPolicy: e.target.checked })}
+ onChange={(e) => setFormData({ ...formData, privacyPolicy: e.target.checked.toString() })}
className="min-w-4 min-h-4 cursor-pointer"
id="privacyPolicy"
required
diff --git a/src/components/auth/PhoneNumberDialog.js b/src/components/auth/PhoneNumberDialog.tsx
similarity index 89%
rename from src/components/auth/PhoneNumberDialog.js
rename to src/components/auth/PhoneNumberDialog.tsx
index c061659b..89b58059 100644
--- a/src/components/auth/PhoneNumberDialog.js
+++ b/src/components/auth/PhoneNumberDialog.tsx
@@ -1,6 +1,6 @@
'use client';
-import React, { useCallback, useEffect, useState } from 'react';
+import React, { FormEvent, useCallback, useEffect, useState } from 'react';
import Modal from '@/components/Modal';
import { authService } from '@/lib/service';
@@ -11,14 +11,18 @@ import { isValidPhone } from '@/helpers/utils';
const MODAL_NAME = 'phone-number';
-const PhoneForm = ({ onSubmit }) => {
+type PhoneFormProps = {
+ onSubmit: (phoneNumber: string, privacyPolicy: string) => void;
+};
+
+const PhoneForm = ({ onSubmit }: PhoneFormProps) => {
const [formData, setFormData] = useState({
phoneNumber: '',
privacyPolicy: '',
});
const handleSubmit = useCallback(
- (e) => {
+ (e: FormEvent) => {
e.preventDefault();
/* PHONE VALIDATION */
@@ -35,7 +39,7 @@ const PhoneForm = ({ onSubmit }) => {
const formatedPhoneNumber = formatPhoneNumber(formData.phoneNumber);
- onSubmit(formData.phoneNumber, formData.privacyPolicy);
+ onSubmit(formatedPhoneNumber, formData.privacyPolicy);
setFormData({
phoneNumber: '',
@@ -45,7 +49,7 @@ const PhoneForm = ({ onSubmit }) => {
[onSubmit, formData],
);
- const handleChange = useCallback((phoneNumber) => {
+ const handleChange = useCallback((phoneNumber: string) => {
setFormData((formData) => ({ ...formData, phoneNumber }));
}, []);
@@ -74,7 +78,7 @@ const PhoneForm = ({ onSubmit }) => {
setFormData({ ...formData, privacyPolicy: e.target.checked })}
+ onChange={(e) => setFormData({ ...formData, privacyPolicy: e.target.checked.toString() })}
className="min-w-4 min-h-4 cursor-pointer"
id="privacyPolicy"
required
@@ -123,7 +127,7 @@ const PhoneNumberDialog = () => {
fetchNumber();
}, []);
- const handleSubmit = useCallback(async (phoneNumber, privacyPolicy) => {
+ const handleSubmit = useCallback(async (phoneNumber: string, privacyPolicy: string) => {
const { data: session, error: errorGettingUser } = await authService.getSessionUser();
if (!session.user || errorGettingUser) {
diff --git a/src/components/auth/SignUp.js b/src/components/auth/SignUp.tsx
similarity index 89%
rename from src/components/auth/SignUp.js
rename to src/components/auth/SignUp.tsx
index 5eec2555..c28d2998 100644
--- a/src/components/auth/SignUp.js
+++ b/src/components/auth/SignUp.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useCallback, useState } from 'react';
+import { FormEvent, useCallback, useState } from 'react';
import { ArrowBigLeft } from 'lucide-react';
import { authService } from '@/lib/service';
@@ -8,21 +8,39 @@ import { PhoneInput } from '@/components/PhoneInput';
import { formatPhoneNumber } from '@/helpers/utils';
import { isValidPhone } from '@/helpers/utils';
-export default function SignUp({ onBackButtonClicked }) {
- const [formData, setFormData] = useState({
+type FormData = {
+ email: string;
+ password: string;
+ telefono: string;
+ nombre: string;
+ privacyPolicy: string;
+};
+
+type Status = {
+ isSubmitting: boolean;
+ error: string | null;
+ success: boolean;
+};
+
+type SignUpProps = {
+ onBackButtonClicked: () => void;
+};
+
+export default function SignUp({ onBackButtonClicked }: SignUpProps) {
+ const [formData, setFormData] = useState({
nombre: '',
email: '',
password: '',
telefono: '',
privacyPolicy: '',
});
- const [status, setStatus] = useState({
+ const [status, setStatus] = useState({
isSubmitting: false,
error: null,
success: false,
});
- const setError = (mensaje) => {
+ const setError = (mensaje: string) => {
setStatus({
isSubmitting: false,
error: mensaje,
@@ -30,11 +48,11 @@ export default function SignUp({ onBackButtonClicked }) {
});
};
- const handlePhoneChange = useCallback((phoneNumber) => {
+ const handlePhoneChange = useCallback((phoneNumber: string) => {
setFormData((formData) => ({ ...formData, telefono: phoneNumber }));
}, []);
- const handleSubmit = async (e) => {
+ const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
/* Form validation */
@@ -84,7 +102,7 @@ export default function SignUp({ onBackButtonClicked }) {
formData.password,
formData.nombre,
formatedPhoneNumber,
- formData.privacyPolicy,
+ Boolean(formData.privacyPolicy),
);
if (response.error) {
@@ -168,7 +186,7 @@ export default function SignUp({ onBackButtonClicked }) {
setFormData({ ...formData, privacyPolicy: e.target.checked })}
+ onChange={(e) => setFormData({ ...formData, privacyPolicy: e.target.checked.toString() })}
className="min-w-4 min-h-4 cursor-pointer"
id="privacyPolicy"
required
diff --git a/src/components/auth/SocialButton.js b/src/components/auth/SocialButton.tsx
similarity index 62%
rename from src/components/auth/SocialButton.js
rename to src/components/auth/SocialButton.tsx
index 4c829a3c..82ddef35 100644
--- a/src/components/auth/SocialButton.js
+++ b/src/components/auth/SocialButton.tsx
@@ -1,12 +1,14 @@
import { supabase } from '@/lib/supabase/client';
import { redirect } from 'next/navigation';
+import { Provider } from '@supabase/auth-js';
+import { ReactNode } from 'react';
-export default function SocialButton({ provider, children }) {
- const providersBg = {
- google: 'red-500',
- };
-
- const handleLogin = async (provider) => {
+type SocialButtonProps = {
+ provider: Provider;
+ children: ReactNode;
+};
+export default function SocialButton({ provider, children }: SocialButtonProps) {
+ const handleLogin = async (provider: Provider) => {
const { data, error } = await supabase.auth.signInWithOAuth({
provider,
});
@@ -23,7 +25,7 @@ export default function SocialButton({ provider, children }) {
return (