Skip to content

Commit

Permalink
feat: use same query to avoid spinners
Browse files Browse the repository at this point in the history
  • Loading branch information
Roberto Milla Martinez committed Nov 16, 2024
1 parent 0bcc252 commit 4450fcd
Show file tree
Hide file tree
Showing 14 changed files with 89 additions and 125 deletions.
8 changes: 4 additions & 4 deletions src/app/casos-activos/solicitudes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useTowns } from '@/context/TownProvider';
import { TabNavigationCount } from '@/components/TabNavigation';
import Modal from '@/components/Modal';
import { MAP_MODAL_NAME } from '@/components/map/map';
import { HelpRequestData } from '@/types/Requests';
import { HelpRequestData, HelpRequestWAssignments } from '@/types/Requests';
import SolicitudCard from '@/components/solicitudes/SolicitudCard';
import SolicitudList, { isStringTrue } from '@/components/solicitudes/SolicitudList';
import SolicitudMap from '@/components/solicitudes/SolicitudMap';
Expand All @@ -28,14 +28,14 @@ function getDataFiltered(data: HelpRequestData[], filters: DataFilter[]) {

type SolicitudesProps = {
count: TabNavigationCount;
data: HelpRequestData[];
data: HelpRequestWAssignments[];
};

export function Solicitudes({ data, count }: SolicitudesProps) {
const { towns } = useTowns();
const searchParams = useSearchParams();
const router = useRouter();
const [selectedMarker, setSelectedMarker] = useState<HelpRequestData | null>(null);
const [selectedMarker, setSelectedMarker] = useState<HelpRequestWAssignments | null>(null);

const [dataFiltered, setDataFiltered] = useState<HelpRequestData[]>(data);

Expand Down Expand Up @@ -98,7 +98,7 @@ export function Solicitudes({ data, count }: SolicitudesProps) {
<div className="lg:flex lg:flex-row-reverse">
<SolicitudMap data={dataFiltered} setSelectedMarker={setSelectedMarker} />
<SolicitudList
data={dataFiltered}
data={dataFiltered as HelpRequestWAssignments[]}
count={count}
filtersData={filtersData}
onDataFilterChange={changeDataFilter}
Expand Down
6 changes: 3 additions & 3 deletions src/app/casos-activos/solicitudes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { createClient } from '@/lib/supabase/server';
import { Database } from '@/types/database';
import { Solicitudes } from '.';
import { helpDataSelectFields, HelpRequestData } from '@/types/Requests';
import { HelpRequestWAssignments } from '@/types/Requests';
import { FiltersData } from './types';

export const dynamic = 'force-dynamic';

function parseData(data: Database['public']['Tables']['help_requests']['Row'][]): HelpRequestData[] {
function parseData(data: Database['public']['Tables']['help_requests']['Row'][]): HelpRequestWAssignments[] {
return data.map((d) => {
// Remove unused properties to reduce the payload size
const { coordinates, location, ...rest } = d;
Expand All @@ -17,7 +17,7 @@ function parseData(data: Database['public']['Tables']['help_requests']['Row'][])
// Fix the coordinates to 3 decimals so locations have a 100m precision
latitude: Number(d.latitude?.toFixed(3)),
longitude: Number(d.longitude?.toFixed(3)),
} as HelpRequestData;
} as HelpRequestWAssignments;
});
}

Expand Down
10 changes: 5 additions & 5 deletions src/app/solicitudes/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,21 @@ import SolicitudCard from '@/components/solicitudes/SolicitudCard';
import { useParams } from 'next/navigation';
import SolicitudComments from '@/components/Comments/SolicitudComments';
import { useEffect, useState } from 'react';
import { SelectedHelpData } from '../../../types/Requests';
import { getOne } from '@/lib/actions';
import { SelectedHelpDataWAssignment } from '../../../types/Requests';
import { getOneWithAssignments } from '@/lib/actions';

export default function CasoDetalle() {
const [loading, setLoading] = useState<boolean>(true);
const [data, setData] = useState<SelectedHelpData | null>(null);
const [data, setData] = useState<SelectedHelpDataWAssignment | null>(null);
const { id } = useParams<{ id: string }>();

useEffect(() => {
async function fetchData() {
try {
setLoading(true);

const requestResponse = await getOne(Number(id));
setData(requestResponse as SelectedHelpData);
const requestResponse = await getOneWithAssignments(Number(id));
setData(requestResponse as SelectedHelpDataWAssignment);

setLoading(false);
} catch (err) {
Expand Down
8 changes: 4 additions & 4 deletions src/app/solicitudes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import SolicitudCard from '@/components/solicitudes/SolicitudCard';
import { useSession } from '@/context/SessionProvider';
import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';
import { SelectedHelpData } from '@/types/Requests';
import { getSolicitudesByUser } from '@/lib/actions';
import { SelectedHelpDataWAssignment } from '@/types/Requests';
import { getSolicitudesWAssignemntsByUser } from '@/lib/actions';

export const dynamic = 'force-dynamic';

Expand All @@ -18,9 +18,9 @@ export default function ListaSolicitudes() {
data: requests,
isLoading,
error,
} = useQuery<SelectedHelpData[]>({
} = useQuery<SelectedHelpDataWAssignment[]>({
queryKey: ['help_requests', { user_id: userId, type: 'necesita' }],
queryFn: () => getSolicitudesByUser(userId || ''),
queryFn: () => getSolicitudesWAssignemntsByUser(userId || ''),
});

if (isLoading) {
Expand Down
16 changes: 8 additions & 8 deletions src/components/AsignarSolicitudButton.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use client';

import { useSession } from '@/context/SessionProvider';
import { HelpRequestAssignmentData, SelectedHelpData } from '@/types/Requests';
import { getAssignments, assign, unassign } from '@/lib/actions';
import { SelectedHelpData, SelectedHelpDataWAssignment } from '@/types/Requests';
import { assign, unassign, getSolicitudesWAssignemntsByUser } from '@/lib/actions';
import { MouseEvent } from 'react';
import { Spinner } from '@/components/Spinner';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
Expand All @@ -23,12 +23,12 @@ export default function AsignarSolicitudButton({ helpRequest }: AsignarSolicitud
const router = useRouter();

const {
data: assignments,
data: solicitudesUser,
isLoading,
error,
} = useQuery<HelpRequestAssignmentData[]>({
queryKey: ['help_request_assignments', { id: helpRequest.id }],
queryFn: () => getAssignments(helpRequest.id),
} = useQuery<SelectedHelpDataWAssignment[]>({
queryKey: ['help_requests', { user_id: userId, type: 'necesita' }],
queryFn: () => getSolicitudesWAssignemntsByUser(userId || ''),
});

const queryClient = useQueryClient();
Expand Down Expand Up @@ -84,9 +84,9 @@ export default function AsignarSolicitudButton({ helpRequest }: AsignarSolicitud
}

if (isLoading) return <Spinner />;
if (error || assignments === undefined) return <></>;
if (error || solicitudesUser === undefined) return <></>;

const userAssignment = assignments.find((x) => x.user_id === session.user?.id);
const userAssignment = solicitudesUser.find((x) => x.id === helpRequest.id);
const userIsAssigned = !!userAssignment;

if (!session || !session.user)
Expand Down
24 changes: 14 additions & 10 deletions src/components/PhoneInfo.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,39 @@
import { useQuery } from '@tanstack/react-query';
import { useSession } from '@/context/SessionProvider';
import { getAssignments } from '@/lib/actions';
import { SelectedHelpData } from '@/types/Requests';
import { getSolicitudesWAssignemntsByUser } from '@/lib/actions';
import { SelectedHelpDataWAssignment } from '@/types/Requests';

type PhoneInfoProps = {
caseInfo: SelectedHelpData;
caseInfo: SelectedHelpDataWAssignment;
isAdmin: boolean;
};
export default function PhoneInfo({ caseInfo, isAdmin }: PhoneInfoProps) {
const session = useSession();
const userId = session?.user?.id;

const {
data: assignments,
data: solicitudesUser,
isLoading,
error,
} = useQuery({
queryKey: ['help_request_assignments', { id: caseInfo.id }],
queryFn: () => getAssignments(caseInfo.id),
} = useQuery<SelectedHelpDataWAssignment[]>({
queryKey: ['help_requests', { user_id: userId, type: 'necesita' }],
queryFn: () => getSolicitudesWAssignemntsByUser(userId || ''),
staleTime: Infinity,
gcTime: Infinity,
});

if (error || isLoading) return <></>;
if (error || isLoading || !solicitudesUser) return <></>;

const userAssignment = assignments?.find((x) => x.user_id === session.user?.id);
const userAssignment = solicitudesUser.find((x) => x.id === caseInfo.id);
const userIsAssigned = !!userAssignment;

return (
<span className="break-words">
<span className="font-semibold">Contacto:</span>{' '}
{session && session.user
? isAdmin
? caseInfo.contact_info
: !!userAssignment
: !!userIsAssigned
? caseInfo.contact_info
: 'Dale al botón "Quiero ayudar" para ver sus datos de contacto.'
: 'Inicia sesion para ver este dato'}
Expand Down
9 changes: 4 additions & 5 deletions src/components/map/map.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
'use client';

import { Dispatch, FC, ReactNode, SetStateAction, useState } from 'react';
import { Dispatch, FC, SetStateAction, useState } from 'react';
import InteractiveMap, { Layer, MapLayerMouseEvent, Source } from 'react-map-gl/maplibre';
import 'maplibre-gl/dist/maplibre-gl.css';
import { useModal } from '@/context/ModalProvider';
import { HelpRequestData } from '@/types/Requests';
import { InterpolationSpecification } from 'maplibre-gl';
import { HelpRequestWAssignments } from '@/types/Requests';

export const MAP_MODAL_NAME = `map-marker`;

type MapProps = {
solicitudes?: GeoJSON.FeatureCollection<GeoJSON.Point>;
setSelectedMarker: Dispatch<SetStateAction<HelpRequestData | null>>;
setSelectedMarker: Dispatch<SetStateAction<HelpRequestWAssignments | null>>;
};

const PAIPORTA_LAT = 39.42333;
Expand All @@ -30,7 +29,7 @@ const Map: FC<MapProps> = ({ solicitudes, setSelectedMarker }) => {
const onClickHandler = (e: MapLayerMouseEvent) => {
if (e.features?.[0]) {
toggleModal(MAP_MODAL_NAME, true);
setSelectedMarker(e.features?.[0].properties as HelpRequestData);
setSelectedMarker(e.features?.[0].properties as HelpRequestWAssignments);
}
};

Expand Down
13 changes: 8 additions & 5 deletions src/components/solicitudes/SolicitudCard.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { AlertTriangle, MapPin, MapPinned, Megaphone, Phone, Users } from 'lucide-react';
import { AlertTriangle, MapPinned, Megaphone, Phone, Users } from 'lucide-react';
import { tiposAyudaOptions } from '@/helpers/constants';
import Link from 'next/link';
import { useSession } from '@/context/SessionProvider';
import { HelpRequestAdditionalInfo, HelpRequestData, SelectedHelpData } from '@/types/Requests';
import { HelpRequestAdditionalInfo, SelectedHelpDataWAssignment } from '@/types/Requests';
import AsignarSolicitudButton from '@/components/AsignarSolicitudButton';
import SolicitudHelpCount from '@/components/solicitudes/SolicitudHelpCount';
import PhoneInfo from '@/components/PhoneInfo';
import DeleteHelpRequest from '../DeleteHelpRequest';
import { textWithEllipsis } from '@/helpers/utils';
Expand Down Expand Up @@ -38,7 +37,7 @@ export const getHighlightedText = (text: string, highlight: string) => {
};

type SolicitudCardProps = {
caso: SelectedHelpData;
caso: SelectedHelpDataWAssignment;
showLink?: boolean;
showEdit?: boolean;
format?: 'small' | 'large';
Expand Down Expand Up @@ -97,7 +96,11 @@ export default function SolicitudCard({
</div>
</div>
<div className="flex flex-row justify-center items-center gap-2">
<SolicitudHelpCount id={caso.id} />
<div
className={`flex items-center justify-center rounded-full px-4 py-2 ${caso.assignments_count === 0 ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'}`}
>
<span className={`text-sm font-bold`}>{caso.assignments_count} VOLUNTARIOS</span>
</div>
<div
className={`flex items-center justify-center rounded-full px-4 py-2 ${
updateStatus === 'finished'
Expand Down
38 changes: 0 additions & 38 deletions src/components/solicitudes/SolicitudHelpCount.tsx

This file was deleted.

6 changes: 3 additions & 3 deletions src/components/solicitudes/SolicitudList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ import { tiposAyudaOptions } from '@/helpers/constants';
import { useTowns } from '@/context/TownProvider';
import { Toggle } from '@/components/Toggle';
import TabNavigation, { TabNavigationCount } from '@/components/TabNavigation';
import { HelpRequestData } from '@/types/Requests';
import { SelectedHelpDataWAssignment } from '@/types/Requests';
import { Virtuoso } from 'react-virtuoso';
import { FiltersData, FilterType } from '@/app/casos-activos/solicitudes/types';

export const isStringTrue = (str: string): boolean => str === 'true';

type SolicitudListProps = {
data: HelpRequestData[];
data: SelectedHelpDataWAssignment[];
count: TabNavigationCount;
filtersData: FiltersData;
onDataFilterChange: (type: FilterType, newFilter: string) => void;
Expand Down Expand Up @@ -130,7 +130,7 @@ export default function SolicitudList({ data, count, filtersData, onDataFilterCh
format="small"
showLink={true}
showEdit={true}
caso={caso as HelpRequestData}
caso={caso}
highlightedText={filtersData.search}
/>
</div>
Expand Down
4 changes: 2 additions & 2 deletions src/components/solicitudes/SolicitudMap.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import Map from '@/components/map/map';
import { HelpRequestData } from '@/types/Requests';
import { HelpRequestData, HelpRequestWAssignments } from '@/types/Requests';
import { Dispatch, SetStateAction, useMemo } from 'react';

function transformHelpRequestToPointFeature(request: any): GeoJSON.Feature<GeoJSON.Point> | [] {
Expand All @@ -20,7 +20,7 @@ function transformHelpRequestToPointFeature(request: any): GeoJSON.Feature<GeoJS

type SolicitudListProps = {
data: HelpRequestData[];
setSelectedMarker: Dispatch<SetStateAction<HelpRequestData | null>>;
setSelectedMarker: Dispatch<SetStateAction<HelpRequestWAssignments | null>>;
};

export default function SolicitudList({ data, setSelectedMarker }: SolicitudListProps) {
Expand Down
38 changes: 0 additions & 38 deletions src/helpers/format.tsx

This file was deleted.

Loading

0 comments on commit 4450fcd

Please sign in to comment.