I have this store (pinia):
actions: {
async addCompany ( company ) {
await axios.post('/api/companies.json', company)
.then( (response) => {
this.companies.push(company);
})
.catch((error) => {
console.log(error);
});
},
And I call it from my component like this:
methods: {
saveRow(item) {
this.store.addCompany(this.editedItem)
},
Everything works ok but now I want to notify the user with toast or Swal or whaterver (I'm using quasar) that everithing was ok or if we got an error. Something like this: Invented code... is what I wanted to achieve:
methods: {
saveRow(item) {
const result = this.store.addCompany(this.editedItem)
if ( result == "OK") {
alert("All good!)
} else {
alert ("HORROR!")
}
},
you know what I meant... but I can not figure out how to do that. Any help or clue?
CodePudding user response:
In your store you can return the promise from axios
itself:
addCompany ( company ) {
return axios.post('/api/companies.json', company)
.then( (response) => {
this.companies.push(company);
})
.catch((error) => {
console.log(error);
});
},
Then in your component you can simply do a .then
just like you did in your store:
import {Notify} from "quasar";
saveRow(item) {
const result = this
.store
.addCompany(this.editedItem)
.then(() => {
Notify.create("Company has been added")
})
.catch(() => {
Notify.create("There was an error adding company")
});
},
Feel free to visit MDN's docs on Javascript Promises