From 218a50307aeb6961a51283e3e48ba46f7dce62c2 Mon Sep 17 00:00:00 2001 From: Alexis <35.alexis.pele@gmail.com> Date: Sun, 30 Apr 2023 16:27:23 +0200 Subject: [PATCH] Added error handling to geoloc --- src/components/GeolocRequest.vue | 31 ++++++++++++++++++++++++++++--- src/main.ts | 9 +++++++-- src/stores/repStore.ts | 10 +++++++--- 3 files changed, 42 insertions(+), 8 deletions(-) diff --git a/src/components/GeolocRequest.vue b/src/components/GeolocRequest.vue index d36de2e..5afb95c 100644 --- a/src/components/GeolocRequest.vue +++ b/src/components/GeolocRequest.vue @@ -2,13 +2,31 @@ import { useRepStore } from "@/stores/repStore"; import { useGeolocation } from "@vueuse/core"; import RepButton from "./RepButton.vue"; +import { computed, ref } from "vue"; const { coords } = useGeolocation(); const { getRep, setRep } = useRepStore(); +const isFetching = ref(false); +const lastError = ref(""); + +const buttonIcon = computed(() => + isFetching.value ? "spinner" : "location-dot" +); + async function handleGeolocClick() { - const rep = await getRep(coords.value.longitude, coords.value.latitude); - setRep(rep); + isFetching.value = true; + + try { + const rep = await getRep(coords.value.longitude, coords.value.latitude); + + setRep(rep); + } catch (err) { + const error = (await err) as Error; + lastError.value = error.message; + } finally { + isFetching.value = false; + } } @@ -20,8 +38,15 @@ async function handleGeolocClick() { - + Géolocalisation +
+ {{ lastError }} +
diff --git a/src/main.ts b/src/main.ts index 1e84cc8..4d9779f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -15,7 +15,11 @@ import { faLinkedin, faInstagram, } from "@fortawesome/free-brands-svg-icons"; -import { faLandmark, faLocationDot } from "@fortawesome/free-solid-svg-icons"; +import { + faLandmark, + faLocationDot, + faSpinner, +} from "@fortawesome/free-solid-svg-icons"; library.add( faTwitter, @@ -23,7 +27,8 @@ library.add( faLinkedin, faInstagram, faLandmark, - faLocationDot + faLocationDot, + faSpinner ); const app = createApp(App); diff --git a/src/stores/repStore.ts b/src/stores/repStore.ts index e4200ba..d56dda8 100644 --- a/src/stores/repStore.ts +++ b/src/stores/repStore.ts @@ -8,9 +8,13 @@ export const useRepStore = defineStore("repStore", () => { const currentRep = ref(null); async function getRep(lon: number, lat: number): Promise { - return fetch(`${apiUrl}/rep?lat=${lat}&lon=${lon}`) - .then((t) => t.json()) - .catch((err) => console.log(err)); + return fetch(`${apiUrl}/rep?lat=${lat}&lon=${lon}`).then(async (res) => { + if (res.ok) { + return res.json(); + } else { + throw res.json().then((res) => new Error(res.message)); + } + }); } function setRep(rep: Depute) {