Reputation: 358
I'm trying to GET
a response from an API endpoint using Axios, but nothing is coming back.
I've tried putting the Axios call in the component and in the Vuex store, but no luck so far.
store.js
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(Vuex);
Vue.use(VueAxios, axios);
export default new Vuex.Store({
state: {
similarTitles: []
},
mutations: {
SIMILAR_TITLES_LIST(state, similarTitles) {
state.similarTitles = similarTitles;
}
},
actions: {
async getSimilarTitles({ commit }, payload) {
console.log("axios begin"); // this shows briefly
await axios
.get(
`https://tastedive.com/api/similar?q=${payload}&type=books&info=1&k=${process.env.VUE_APP_TASTE_DIVE_API_KEY}`
)
.then(data => {
console.log("did i get here?"); // this never shows
console.log(data.Similar.Results); // or this
commit("SIMILAR_TITLES_LIST", data.Similar.Results); // not surprising that this doesn't put info into state
});
console.log("axios end"); // this shows briefly
}
}
});
Recommender.vue
<template>
<div class="recommender">
<h1>Oscar's Book Recommendations!</h1>
<form class="findTitle">
<label for="enjoyedTitle">What's the name of a book you liked?</label>
<br />
<input type="text" id="enjoyedTitle" v-model="enjoyedTitle" />
<br />
<button @click="findSimilarTitles">Find a new book!</button>
</form>
</div>
</template>
<script>
export default {
name: "Recommender",
data() {
return {
enjoyedTitle: ""
};
},
methods: {
async findSimilarTitles() {
await this.$store.dispatch("getSimilarTitles", this.enjoyedTitle);
}
}
};
</script>
<style scoped lang="scss">
.recommender {
display: flex;
flex-flow: column nowrap;
form {
display: flex;
flex-flow: column nowrap;
align-self: center;
width: 21em;
button {
align-self: center;
width: 10em;
}
}
}
</style>
This is failing silently. The console.log
statements before and after the Axios call briefly show in the console, but then the component resets and all console statements disappear. The console.log
statements inside the Axios call never show. I know this can work somehow, otherwise the internet won't do anything. Can somebody point out what I'm not seeing?
Appreciate the help! Thanks!
Upvotes: 1
Views: 986
Reputation: 1049
You should catch like
async getSimilarTitles({ commit }, payload) {
console.log("axios begin"); // this shows briefly
await axios
.get(
`https://tastedive.com/api/similar?q=${payload}&type=books&info=1&k=${process.env.VUE_APP_TASTE_DIVE_API_KEY}`
)
.then(data => {
console.log("did i get here?"); // this never shows
console.log(data.Similar.Results); // or this
commit("SIMILAR_TITLES_LIST", data.Similar.Results); // not surprising that this doesn't put info into state
}).catch(err => {
console.log('Call Failed!');
console.log(err);
});
console.log("axios end"); // this shows briefly
}
}
Upvotes: 2