I have been working on updating my API array by using axios and Vue.js. My goal is to implement the functionality that allows me to add a new object and have it displayed on the timeline. However, I am facing an issue where when I try to post a new title, I can see the object in the console.log but it is not being added to the correct array from the API, as there is no new ID associated with the object.
Index.html
<body>
<div id="app">
<template>
<form @submit.prevent>
<input type="text" v-model="postBody"/>
<button type="button" class="btn btn-primary pull-right" data-toggle="modal" @click="postPost()">Post Title</button>
</form>
<ul v-if="errors && errors.length">
<li v-for="error of errors">
{{error.message}}
</li>
</ul>
</template>
<br>
<!-- <p>{{ status }}</p> -->
<template v-for="(results, index) in result">
<div class="card" style="width: 20rem; display:inline-block;">
<div class="card-block">
<p>{{ results.id }}</p>
<p>{{ results.title }}</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> -->
<button type="button" class="btn btn-danger pull-right" data-toggle="modal" @click="deleteData(results, index)">Delete</button>
<h1> {{ results.comments}} </h1>
</div>
</div>
</template>
</div>
</body>
Main.js
var vm = new Vue ({
el: '#app',
data: {
result: '',
title: '',
data: '',
postBody: '',
User: { title: '' },
errors: []
},
created: function(){
this.getResult();
},
methods: {
getResult: function() {
// this.results = 'Loading...';
axios.get('https://my-json-server.typicode.com/shaneogrady/json/db')
.then(response => {
// console.log(response.data);
this.result = response.data.posts;
console.log(this.result);
});
},
deleteData: function(result, id) {
axios.delete('https://my-json-server.typicode.com/shaneogrady/json/posts/' + result.id)
.then(response => {
this.result.splice(id, 1)
console.log(this.result);
});
},
postPost() {
axios.post('https://my-json-server.typicode.com/shaneogrady/json/posts/', {
// id: 4,
// title: 'Shane',
body: this.postBody
})
.then(response => { console.log(response.data); this.result.push(response.data) })
.catch(e => {
this.errors.push(e)
})
}
}
});