问题
How to check if my api request returns me any data from fetchData
function?, I want to return boolean
(or something else) to my Index.vue
and show loader when data is loading but when data is loaded then i want to use: this.$router.push("admin/dashboard")
to redirect to another page where this data is displayed,
my code:
const actions = {
fetchData({ commit },{ id}) {
return axios.get(`someUrl?hd=${id}`)
.then(response => {
if(response.status == 200) {
commit('setData', response.data),
}
})
.catch(
error => {
console.log(error);
}
);
}
}
Index.vue
<div v-if="isDataLoaded" class="loading-div">
<vue-spinner />
</div>
methods: {
...mapActions(["fetchData"]),
launchFetchData() {
new Promise(() => {
this.$store.dispatch("fetchData", {
id: this.id
})
})
}
thanks for any help
回答1:
you can use: console.log(response.data)
回答2:
When you set your data to response.data, use the .length to check the size. If it's > 0 then route the user to the dashboard.
回答3:
Use Js Promises in this way.. The next all statements will pause until the promise resolve an issue
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
function makeGetRequest(path) {
return new Promise(function (resolve, reject) {
axios.get(path).then(
(response) => {
var result = response.status;
console.log('Processing Request');
resolve(result);
},
(error) => {
reject(error);
}
);
});
}
async function main() {
var result = await makeGetRequest('https://jsonplaceholder.typicode.com/users/1');
console.log("Status ", result);
console.log('Statement 1');
console.log('Statement 2');
}
main();
console.log('starting....');
</script>
</body>
reference: https://www.geeksforgeeks.org/how-to-make-javascript-wait-for-a-api-request-to-return/
来源:https://stackoverflow.com/questions/65672888/how-to-check-if-data-is-returned-from-api