API connection error handling

This commit is contained in:
2020-12-07 00:36:36 +01:00
parent de853c4a96
commit 5d34725344
3 changed files with 46 additions and 6 deletions

View File

@@ -2,8 +2,14 @@ import axios from "axios";
export default { export default {
getFruits: async ({ commit }) => { getFruits: async ({ commit }) => {
const response = await axios.get("http://localhost:3000/fruit"); await axios
commit("setFruits", response.data.data); .get("http://localhost:3000/fruit")
.then(res => {
commit("setFruits", res.data.data);
})
.catch(err => {
if (err.message === "Network Error") throw "Check API connectivity ...";
});
}, },
getFruit: async ({ commit }, id) => { getFruit: async ({ commit }, id) => {
const response = await axios.get(`http://localhost:3000/fruit/${id}`); const response = await axios.get(`http://localhost:3000/fruit/${id}`);

View File

@@ -128,7 +128,7 @@ article {
.alert { .alert {
margin-top: 1.75rem; margin-top: 1.75rem;
background-color: lighten(@color-1, 10%); background: linear-gradient(112.4deg, #1c9797 11.05%, #147171 89.93%);
color: @color-2; color: @color-2;
padding: 1rem 1.5rem; padding: 1rem 1.5rem;
border-radius: 4px; border-radius: 4px;

View File

@@ -1,7 +1,11 @@
<template> <template>
<div class="fruits"> <div class="fruits">
<h2>Directory</h2> <h2>Directory</h2>
<Grid :data="this.fruits" /> <Grid v-if="!error" :data="this.fruits" />
<div class="alert" v-else>
{{ error }}
<pre><span>$</span> yarn run api</pre>
</div>
</div> </div>
</template> </template>
@@ -15,15 +19,45 @@ export default {
computed: { computed: {
...mapState(["fruits"]) ...mapState(["fruits"])
}, },
data() {
return {
error: null
};
},
async created() { async created() {
await this.$store.dispatch("getFruits"); await this.$store.dispatch("getFruits").catch(err => (this.error = err));
} }
}; };
</script> </script>
<style lang="less"> <style scoped lang="less">
.fruits { .fruits {
margin: 0 auto; margin: 0 auto;
max-width: 1200px; max-width: 1200px;
} }
.alert {
box-sizing: border-box;
margin: 0 auto;
width: 80%;
background-color: #d63031;
color: @color-2;
padding: 1rem 1.5rem;
border-radius: 4px;
@media screen and (min-width: @sm) {
width: 50%;
max-width: 535px;
}
pre {
padding: 1rem;
border-radius: 4px;
background-color: rgb(45, 48, 55);
span {
color: @color-3;
}
}
}
</style> </style>