I have an issue where my axios.delete method is deleting the wrong objects in the array. There are 3 objects total, coming from an api, the objects with id 2 and 3 fine when I delete in the index.html file, but it throws a 'Uncaught (in promise) Error: Request failed with status code 404' error when I try to delete the first object in the array coming from my API.
My index file (includes the delete button)
<body>
<div id="app">
<template v-for="(results, index) in result">
<div class="card" style="width: 20rem; display:inline-block;">
<div class="card-block">
<p>{{ results }}</p>
<button type="button" class="btn btn-danger pull-right" data-toggle="modal" v-on:submit.prevent="deleteData(index)" @click="deleteData(results, index) in result">Delete</button>
<h1> {{ results.comments}} </h1>
</div>
</div>
</template>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue"></script>
<script src="src/main.js"></script>
Main.js
var vm = new Vue ({
el: '#app',
data: {
result: ''
},
created: function(){
this.getResult();
},
methods: {
deleteData: function(result, id) {
axios.delete('https://my-json-server.typicode.com/json/posts/' + id)
.then(response => {
this.result.splice(id, 1)
console.log(this.result);
});
},
getResult: function() {
// this.results = 'Loading...';
axios.get('https://my-json-server.typicode.com/json/db')
.then(response => {
// console.log(response.data);
this.result = response.data.posts;
console.log(this.result);
});
}
}
});
3 Answers 3
as I can see, you pass two params to your deleteData method. the second param it's the index of results array it's not your real id of results.
here, you just need to replace your deleteData method by this :
deleteData: function(result, id) {
axios.delete('https://my-json-server.typicode.com/json/posts/' + result.id)
.then(response => {
this.result.splice(id, 1)
console.log(this.result);
});
},
as you can see above,we have just changed your id by result.id
Comments
change
<button type="button" class="btn btn-danger pull-right" data-toggle="modal" v-on:submit.prevent="deleteData(index)" @click="deleteData(results, index) in result">Delete</button>
to
<button type="button" class="btn btn-danger pull-right" data-toggle="modal" @click="deleteData(results, index)">Delete</button>
Comments
It's a 404 error meaning the it's unable to the page. It might be the link is incorrect. Please look at the url once again! The same thing happened with me, then I realized the URL which I was trying to reach was incorrect.