Reputation: 1054
I use the "then" and "catch" function on Promise Object without using asynchronous functions for easy and manageable parts of response instead of using the await and conditional if-else then check the status if is not a server-side error but I'm a bit confused on how to manage the "then" method of Promise Object to auto-refresh the data that has been fetch through created function and redefined in "then" method using filter without fetching again the data's on the backend side.
export default {
name: 'App',
components: {
Header,
Tasks,
AddTask
},
data() {
return {
tasks : [],
showAddTask : false
}
},
methods : {
deleteTask(index)
{
const that = this;
const res = fetch(`api/tasks/${index}`, {
method : "DELETE"
});
res.catch(e => alert("Error deleting task"));
res.then(function() {
/**
* this is a part where I am a bit confused
**/
that.tasks.filter(e => e.id !== index)
/**
* I use this method but it is not working
**/
that.$forceUpdate();
});
return res;
},
async fetchTask()
{
const res = await fetch("api/tasks");
const data = await res.json();
return data;
},
},
async created() {
this.tasks = await this.fetchTask();
}
}
Upvotes: 0
Views: 1708
Reputation: 138216
Array.prototype.filter
returns a subset of the original array. It doesn't mutate the array in place, so you have to assign filter
's return value to this.tasks
.
Also, no need to assign that = this
. Just use arrow functions to capture the Vue instance context.
deleteTask()
should look like this:
export default {
methods: {
deleteTask(index) {
fetch(`api/tasks/${index}`, {
method : "DELETE"
}).then(() => {
this.tasks = this.tasks.filter(e => e.id !== index)
}).catch(e => alert("Error deleting task"));
}
}
}
Upvotes: 2
Reputation: 5118
I notice a few things here.
One, you don't need an if-else when using async/await. The async/await equivalent of a promise then/catch is a try/catch block:
try {
const res = await fetch(...);
// Do something with res (response)
} catch (err) {
// Equivalent to promise catch, handle the error (err)
}
Second, if you use arrow functions in your current callbacks you don't need to capture const that = this
. And your syntax is strange, you should ideally chain the .then and .catch:
fetch(...)
.then((res) => { // this is an arrow function
this.tasks...
})
.catch((err) => { // again an arrow function
// Handle the error
});
Finally, Array.prototype.filter
returns a new array with the filtered items. Since you're not using the result of that.tasks.filter
nothing is really happening. Instead, do:
this.tasks = this.tasks.filter(...)
Upvotes: 2