How to use if else before .then() .catch() in Vue.js? - vue.js

I'm creating app in Vue.js. I have two similar methods:
editTool() {
return ToolService.editTool(this.id, this.editedItem)
.then((response) => {
this.$refs.dialogInfo.setSuccess(response);
})
.catch((error) => {
this.$refs.dialogInfo.setError(error);
})
.finally(() => {
this.$emit("completed");
});
},
newTool() {
return ToolService.addTool(this.editedItem)
.then((response) => {
this.$refs.dialogInfo.setSuccess(response);
})
.catch((error) => {
this.$refs.dialogInfo.setError(error);
})
.finally(() => {
this.$emit("completed");
});
},
They only differ in the value in return, rest is the same. I want to turn these two methods into one. I tried this way:
newMethod() {
if (this.edit) return ToolService.editTool(this.id, this.editedItem);
else
return ToolService.addTool(this.editedItem)
.then((response) => {
this.$refs.dialogInfo.setSuccess(response);
})
.catch((error) => {
this.$refs.dialogInfo.setError(error);
})
.finally(() => {
this.$emit("completed");
});
},
But it doesn't work correct. How to do it?

Try in the following way.
editTool() {
return ToolService.editTool(this.id, this.editedItem)
},
newTool() {
return ToolService.addTool(this.editedItem)
},
newMethod() {
let method = this.newTool;
if (this.edit) method = this.editTool;
return method().then((response) => {
this.$refs.dialogInfo.setSuccess(response);
})
.catch((error) => {
this.$refs.dialogInfo.setError(error);
})
.finally(() => {
this.$emit("completed");
});
}

Related

How To Use Emit in Vue.Js?

In this code, I use Random Axios Data in getMembers function.
I wonder if I use the same Data in getMember. As far as I know in this case I can use this.$emit
but I have no idea how to use this.
I want to get exact data in getMember(idx)
methods: {
getMembers() {
var vm = this;
this.axios.get('https://randomuser.me/api/?results=5')
.then(res => {
vm.members = res.data.results;
console.log(vm.members);
})
.catch(error => {
console.log(error);
})
},
getMember(idx) {
this.modal = true;
var vm = this;
console.log(idx);
this.axios.get('https://randomuser.me/api/')
.then(res => {
vm.member = res.data.results;
console.log(vm.member);
})
.catch(error => {
console.log(error);
})
},
},
};

use a function in action of auth modules in wizard module in vuex in vue

I have this function in auth.module.js:
async [VERIFY_AUTH](context) {
if (JwtService.getToken()) {
ApiService.setTokenAxios();
return (
ApiService.get("api/customer/me")
.then(({ data }) => {
console.log("auth request - useer:", data);
context.commit(SET_AUTH, data);
})
///////////
.catch(({ response }) => {
console.log(response);
context.commit(SET_ERROR, serviceErrors(response.data));
})
);
} else {
context.commit(PURGE_AUTH);
}
},
I want dispatch it in wizard.modules.js
[SPOUSES](context, data) {
console.log(data);
return new Promise(() => {
ApiService.post(`api/customer/${data.id}/spouses`, data.form).then(
({ data }) => {
console.log(data);
context.dispatch("auth/VERIFY_AUTH", null, { root: true });
}
);
});
},
I try it but it dont work
do you know what should I do?

Getting JSON info from API

I'm using Axios(Apisauce) to connect API to React Native App;
this is the JSON file I'm trying to show in-app using FlatList :
{
"data": {
"sideMenu": {
"url": "https://google.com",
"icons": [
{
"id": 1,
"url": "https://google.com",
"status": 1
},
]
},
}
}
when I try to log it into the console, using console.log(response.data) returns all API info, but using console.log(response.data.data) doesn't return the object I'm looking for!
I've tried JSON.stringify() or toString() but none of them seem to Work.
my Axios Code :
const getServices = () => {
const service = "https://api.team-grp.ir/app/json/services2.json/";
return client.get(service);
};
My Source Code:
const ServiceInfo = async () => {
await getServices()
.then((response) => {
if (response.ok) {
setServicesData(response.data.data);
}
})
.catch((error) => {
console.warn(error);
setServicesData([]);
});
};
useEffect(() => {
ServiceInfo();
});
you should not use async/await with .then/.cache ...
this code is working for me:
(you can also see my sample code image at the bottom of this answer with a fake getService function, and you will see that logged response is correct)
const ServiceInfo = () => {
getServices().then((response) => {
if (response.ok) {
setServicesData(response.data.data);
}
})
.catch((error) => {
console.warn(error);
setServicesData([]);
});
};
useEffect(() => {
ServiceInfo();
}, []);
const ServiceInfo = async () => {
await getServices()
.then((response) => {
return response.json();
})
.then((response) => {
setServicesData(response.data);
})
.catch((error) => {
console.warn(error);
setServicesData([]);
});
};
Try this

Asynchronous VuexFire Data Fetch With Then/Catch

Given the following functioning vuex action named init that fetches a settings and an accounts collection:
actions: {
init: firestoreAction(({ bindFirestoreRef, commit }, payload) => {
bindFirestoreRef(
'settings', fb.settings.doc(payload),
)
.then(() => commit('SETTINGS_READY', true))
.catch((err) => {
commit('SNACKBAR_TEXT', err.message);
Sentry.captureException(err);
});
bindFirestoreRef(
'accounts', fb.accounts.where('program', '==', payload),
)
.then(() => commit('ACCOUNTS_READY', true))
.catch((err) => {
commit('SNACKBAR_TEXT', err.message);
Sentry.captureException(err);
});
}),
},
I have two questions:
The code appears to run synchronously, but I want the two collections to be fetched asynchronously to maximize performance. How can that be achieved?
Is it possible to refactor this code to be more concise and yet provide for the independent (and synchronous) then/catch functionality present in the example?
You can use async / await function then call the bindFirestoreRef inside Promise constructor.
actions: {
init: firestoreAction(async ({ bindFirestoreRef, commit }, payload) => {
await Promise((resolve, reject) => {
bindFirestoreRef('settings', fb.settings.doc(payload))
.then((res) => {
commit('SETTINGS_READY', true);
resolve(res);
})
.catch((err) => {
commit('SNACKBAR_TEXT', err.message)
Sentry.captureException(err)
reject(err)
})
})
await new Promise((resolve, reject) => {
bindFirestoreRef('accounts', fb.accounts.where('program', '==', payload))
.then((res) => {
commit('ACCOUNTS_READY', true);
resolve(res);
})
.catch((err) => {
commit('SNACKBAR_TEXT', err.message)
Sentry.captureException(err)
reject(err)
})
})
})
},

How do I write a perfect vue.js action to fetch data from server with proper error handling?

export const fetchEnvironmentsData = ({ commit }, params) => {
Vue.http.get('/environments', { params })
.then(response => response.json())
.then(data => {
if (data) {
commit('mutateUpdateEnvironmentData', data);
}
}).catch(function(error) {
alert('Could not load data, Please try again later');
});
};
How do I handle internal server error and empty response from server?
const error = () => alert('Could not load data, Please try again later');
Vue.http.get('/environments', { params })
.then(response => {
const data = response.json();
if (data) {
commit('mutateUpdateEnvironmentData', data);
} else {
error();
}
}, error);
or
Vue.http.get('/environments', { params })
.then(response => response.json(), () => null)
.then(data => {
if (data) {
commit('mutateUpdateEnvironmentData', data);
} else {
alert('Could not load data, Please try again later');
}
});