Added error handling to geoloc

This commit is contained in:
Alexis
2023-04-30 16:27:23 +02:00
parent 807004a67b
commit 218a50307a
3 changed files with 42 additions and 8 deletions

View File

@@ -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<boolean>(false);
const lastError = ref<string>("");
const buttonIcon = computed(() =>
isFetching.value ? "spinner" : "location-dot"
);
async function handleGeolocClick() {
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;
}
}
</script>
@@ -20,8 +38,15 @@ async function handleGeolocClick() {
</h1>
</header>
<RepButton @click="handleGeolocClick" :style="'btn-red'">
<font-awesome-icon :icon="['fass', 'location-dot']" size="lg" />
<font-awesome-icon
:icon="['fass', buttonIcon]"
size="lg"
:class="{ 'fa-spin': isFetching }"
/>
<span>Géolocalisation</span>
</RepButton>
<div v-if="lastError" class="mt-4 max-w-lg mx-auto text-sm text-red-400">
{{ lastError }}
</div>
</section>
</template>

View File

@@ -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);

View File

@@ -8,9 +8,13 @@ export const useRepStore = defineStore("repStore", () => {
const currentRep = ref<Depute | null>(null);
async function getRep(lon: number, lat: number): Promise<Depute> {
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) {