From 31666d9698b0edf5372e84f662d18554c6dfda4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luc=C3=A0s?= Date: Thu, 18 May 2023 13:59:33 +0200 Subject: [PATCH] fix(map): Fix logout Took 1 hour 16 minutes --- src/components/ErrorGeoLocation.tsx | 2 +- src/components/ErrorPage.tsx | 2 +- src/components/Navbar.tsx | 5 +- src/components/layout/map/MapComponent.tsx | 76 ++++---- src/pages/api/auth/[...nextauth].ts | 4 +- src/pages/map.tsx | 207 ++++++--------------- 6 files changed, 99 insertions(+), 197 deletions(-) diff --git a/src/components/ErrorGeoLocation.tsx b/src/components/ErrorGeoLocation.tsx index 5a9c749..9a0d82a 100644 --- a/src/components/ErrorGeoLocation.tsx +++ b/src/components/ErrorGeoLocation.tsx @@ -2,7 +2,7 @@ import { MdError } from "react-icons/md"; import { Button, Text, VStack } from "@chakra-ui/react"; import { useRouter } from "next/router"; -export default function LoadingPage() { +export default function ErrorGeoLocation() { const router = useRouter(); return ( diff --git a/src/components/ErrorPage.tsx b/src/components/ErrorPage.tsx index a5da9da..0e6988a 100644 --- a/src/components/ErrorPage.tsx +++ b/src/components/ErrorPage.tsx @@ -2,7 +2,7 @@ import { MdError } from "react-icons/md"; import { Button, Text, VStack } from "@chakra-ui/react"; import { useRouter } from "next/router"; -export default function LoadingPage() { +export default function ErrorPage() { const router = useRouter(); return ( diff --git a/src/components/Navbar.tsx b/src/components/Navbar.tsx index 7e778d5..87af49a 100644 --- a/src/components/Navbar.tsx +++ b/src/components/Navbar.tsx @@ -29,10 +29,7 @@ export default function Navbar({variant = 'fixed'}: Props) { return ( - {status === 'authenticated' - ? authenticatedLinks - : <> - } + {status === 'authenticated' && authenticatedLinks} ); }; diff --git a/src/components/layout/map/MapComponent.tsx b/src/components/layout/map/MapComponent.tsx index a65f5a3..ab9c46a 100644 --- a/src/components/layout/map/MapComponent.tsx +++ b/src/components/layout/map/MapComponent.tsx @@ -1,7 +1,6 @@ -import {MapContainer, TileLayer, Marker, Popup} from 'react-leaflet'; +import {MapContainer, TileLayer, Marker} from 'react-leaflet'; import {Flex, Text, useToast} from '@chakra-ui/react'; -import MarkerClusterGroup - from '@christopherpickering/react-leaflet-markercluster'; +import MarkerClusterGroup from '@christopherpickering/react-leaflet-markercluster'; import '@christopherpickering/react-leaflet-markercluster/dist/styles.min.css'; @@ -15,46 +14,45 @@ export default function MapComponent(props: any) { const idToastError = 'error_location'; - const userIcon = new L.Icon({ - iconUrl: 'logo.svg', - iconSize: [35, 35], - }); + const userIcon = new L.Icon({iconUrl: 'logo.svg', iconSize: [35, 35]}); + + if (!location[0] || !location[1]) return ( + <> + {!toast.isActive(idToastError) && + toast({ + title: 'Erreur', + id: idToastError, + description: 'Veuillez autoriser la localisation', + status: 'error', + isClosable: false, + duration: 100000, + })} + + Veuillez autoriser la localisation + + + ); return ( <> - {location[0] === null || location[1] === null ? ( - <> - {!toast.isActive(idToastError) && - toast({ - title: 'Erreur', - id: idToastError, - description: 'Veuillez autoriser la localisation', - status: 'error', - isClosable: false, - duration: 100000, - })} - - Veuillez autoriser la localisation - - - ) : ( - - - - {/* Pour le user */} - + + + + {/* Pour le user */} + - - {listBars.map((bar: any, index: number) => )} - - - - )} + + {listBars.map((bar: any, index: number) => + + )} + + + ); } diff --git a/src/pages/api/auth/[...nextauth].ts b/src/pages/api/auth/[...nextauth].ts index fd7aaa6..659825d 100644 --- a/src/pages/api/auth/[...nextauth].ts +++ b/src/pages/api/auth/[...nextauth].ts @@ -55,7 +55,5 @@ export default async function auth(req: NextApiRequest, res: NextApiResponse) { } async function getUserByEmail(email: string): Promise { - return prismaClient.user.findUnique({ - where: {email}, - }); + return prismaClient.user.findUnique({where: {email}}); } \ No newline at end of file diff --git a/src/pages/map.tsx b/src/pages/map.tsx index 5bcb0e8..8cf251a 100644 --- a/src/pages/map.tsx +++ b/src/pages/map.tsx @@ -1,168 +1,77 @@ -import { useEffect, useState } from "react"; -import dynamic from "next/dynamic"; -import { useToast } from "@chakra-ui/react"; -import "leaflet/dist/leaflet.css"; -import { useSession } from "next-auth/react"; -import { useMutation, useQuery } from "@tanstack/react-query"; +import {useEffect, useState} from 'react'; +import dynamic from 'next/dynamic'; +import 'leaflet/dist/leaflet.css'; +import {useSession} from 'next-auth/react'; -import LoadingPage from "@/components/LoadingPage"; -import ErrorPage from "@/components/ErrorPage"; -import ErrorGeolocation from "@/components/ErrorGeolocation"; -import Navbar from "@/components/Navbar"; +import LoadingPage from '@/components/LoadingPage'; +import Navbar from '@/components/Navbar'; +import {Session} from '@/models/auth/Session'; +import ErrorGeoLocation from '@/components/ErrorGeoLocation'; export default function Map() { - const [location, setLocation] = useState([ - null as unknown as number, - null as unknown as number, - ]); - + const [location, setLocation] = useState([]); const [geolocationError, setGeolocationError] = useState(false); - const toast = useToast({ position: "bottom" }); - const idSaveToast = "saved_location"; - const { data: session, status } = useSession(); - const [listBars, setListBars] = useState({} as unknown as any); - - const { - isLoading, - isError, - data: loggedUser, - error, - } = useQuery({ - queryKey: ["LoggedUser"], - enabled: status === "authenticated", - queryFn: async () => { - const { user } = session as unknown as Session; - - return fetch(`/api/users/${user.id}`) - .then((res) => { - return res.json(); - }) - .catch((err) => { - return err; - }); - }, - }); - - const { - data, - isError: isErrorListBars, - isLoading: isLoadingListBars, - error: errorListBars, - } = useQuery({ - queryKey: ["listBars"], - enabled: !isLoading && location[0] !== null, - queryFn: async () => { - let urlBars = new URL( - "https://data.opendatasoft.com/api/v2/catalog/datasets/osm-fr-bars%40babel/exports/json?" - ); - - const coordinates = location[1].toString() + " " + location[0].toString(); - - urlBars.searchParams.append( - "where", - `distance(geo_point_2d,geom'POINT(${coordinates})',75km)` - ); - urlBars.searchParams.append("limit", "-1"); - urlBars.searchParams.append("offset", "0"); - urlBars.searchParams.append("timezone", `UTC`); - - return fetch(urlBars.toString()) - .then((res) => res.json()) - .catch((err) => { - return err; - }); - }, - onSuccess: (data) => { - // filter data where name is not null - const filteredData = data.filter((bar: any) => bar.name !== null); - setListBars(filteredData); - }, - }); - - const userSetLocation = useMutation({ - mutationKey: "userSetLocation", - mutationFn: async (position: string) => { - const pos = { - location: position, - }; - - return fetch(`/api/users/${loggedUser.id}`, { - method: "PATCH", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(pos), - }) - .then((res) => { - // if (!toast.isActive(idSaveToast)) { - // toast({ - // id: idSaveToast, - // title: "Position enregistrée", - // description: "Votre position a bien été enregistrée", - // status: "success", - // }); - // } - res.json(); - }) - .catch((err) => { - return err; - }); - }, - }); - - const geolocationOptions = { - enableHighAccuracy: true, - timeout: 5000, - maximumAge: 0, - }; + const {data: session, status} = useSession({required: true}); + const [listBars, setListBars] = useState(null); useEffect(() => { + if (!session?.user) return; + navigator.geolocation.getCurrentPosition( - successPosition, - errorPosition, - geolocationOptions + (position: GeolocationPosition) => { + setLocation([position.coords.latitude, position.coords.longitude]); + setGeolocationError(false); + }, + () => setGeolocationError(true), + { + enableHighAccuracy: true, + timeout: 5000, + maximumAge: 0, + }, ); - }, [loggedUser]); + if (location[0]) { + let urlBars = new URL('https://data.opendatasoft.com/api/v2/catalog/datasets/osm-fr-bars%40babel/exports/json'); - function successPosition(position: GeolocationPosition) { - setLocation([position.coords.latitude, position.coords.longitude]); - setGeolocationError(false); + const coordinates = `${location[1]} ${location[0]}`; + const params = { + where: `distance(geo_point_2d,geom'POINT(${coordinates})',75km)`, + limit: '-1', + offset: '0', + timezone: 'UTC', + }; - if (!loggedUser) return; - userSetLocation.mutate( - `${position.coords.latitude},${position.coords.longitude}` - ); - } + for (const [key, val] of Object.entries(params)) { + urlBars.searchParams.append(key, val); + } - function errorPosition(error: GeolocationPositionError) { - setGeolocationError(true); - } + fetch(urlBars) + .then(res => res.json()) + .then(data => { + const filteredBars = data.filter((bar: any) => bar.name !== null); + setListBars(filteredBars); + }) + .catch(err => console.error(err)); + } + }, [session?.user]); + + if (status === 'loading') return ; + const {user} = session as unknown as Session; const MapWithNoSSR = dynamic( - () => import("../components/layout/map/MapComponent"), - { - ssr: false, - } + () => import('../components/layout/map/MapComponent'), + {ssr: false}, ); + if (geolocationError) return ; + if (!listBars) return ; + return ( - <> - {geolocationError ? ( - - ) : isError || isErrorListBars ? ( - - ) : isLoading || isLoadingListBars ? ( - - ) : ( - <> - - + + - - )} - + loggedUser={user} + listBars={listBars}/> + ); }