[Vuejs]-VueJs, how to refresh the data that has been fetch through created function

2👍

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"));
    }
  }
}

demo

👤tony19

2👍

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(...)
👤Matt U

Leave a comment