Added error handling to geoloc
This commit is contained in:
@@ -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() {
|
||||
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;
|
||||
}
|
||||
}
|
||||
</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>
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user