Utilizing Vue.js and Axios to Send Object to API

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

  }
  });

Answer №1

Consider using @submit.prevent within the form element

<div id="app">
        <form @submit.prevent>   
            <h4> Add Title</h4>

            <div class="form-group">
              <label class="pull-left"> Title </label>
              <input type="text" class="form-control" placeholder="Title " v-model="User.title">
            </div>
          <button type="submit" class="btn btn-large btn-block btn-primary" @click="postPost">Submit</button>
    </form>
...

Answer №2

if you want to retrieve results after creating a new object, simply call your getResult function within the postPost function

for example:

postPost() {
  axios.post('https://my-json-server.typicode.com/shaneogrady/json/posts/', {
    // id: 4,
    // title: 'Shane',  
    body: this.postBody
  })
  .then(response => {
    this.getResult();
    console.log(response.data);
  })
  .catch(e => {
    this.errors.push(e)
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble receiving time increments while utilizing the datetimepicker

I am using a datetime picker with jQuery and I would like to only select the time without the date. When I click on the input, I am only able to pick hours. How can I fix this? $(document).ready(function() { $.datetimepicker.setDateFormatter(&a ...

Create a JavaScript variable that is initialized with a value from an AngularJS scope

What is the best way to assign a value from an AngularJS scope variable to a JavaScript variable? For example: xyz.controller({ $scope.country = "Canada"; }); Here's how you can do it in JavaScript: <script> var country = {{scope.countr ...

Tips for preserving information in the shape of Mongodb Nested schema with the help of mongoose

I am looking to design the MongoDB structure in a specific way for storing data. Here is an example of how I want it to be structured: ... After some research, this is what I have come up with for the structure: ... If I use the code below to save ...

Dynamic display without AJAX

I need assistance with two drop-down lists where the second list's values should change based on the selection made in the first list. The current set up of the drop-down lists is as follows: <select name="first"> <option name="a" va ...

Discover the proper technique to display an error message in cases where no data is detected during the filtering process

I'm currently working on a component that involves search filtering and dropdown filtering. The filtering functionality is working fine, but I'm struggling to determine where to display an error message if no data is found during the filtering pr ...

Merge all the files into one without applying any compression

I am new to using GruntJS and I am currently adding Uglify to my project. I have configured it to compile all of my JS into one file, but during development, I would like it to not compress the code. After looking at the documentation, I see there is a b ...

Submit the form first and then proceed to download another webpage

I have an idea for creating a tool that can accomplish two tasks: Set the language and date on a specific web form: , and Download the text from another page on the same site while retaining these settings. For example, . This tool should simulate a ...

Users are reporting that verification emails are not being sent when the Accounts.createUser function is used within

I have a simple meteor method set up to create user accounts. In my server/methods.js file: Meteor.methods({ createUserAccount: function(user) { return Accounts.createUser(user); } }); Then in my server/init.js file: Meteor.startup(function() ...

Having trouble updating state with useEffect in a React functional component

Currently, I am dealing with a React functional component that is calling an API to fetch data. The response from the API call is confirmed to be received successfully. My aim is to store this data in an array within the component's state so that it c ...

What is the process for assigning one file input to another file input?

Quite an unusual question, I admit. The crux of the matter is my utilization of a fantastic tool known as cropit. With this tool, we have the ability to upload an image, preview it, and then manipulate it according to our preferences. HTML: <div align ...

Ways to identify when a browser has disabled JavaScript and present a notification

Is there a way to detect if JavaScript is disabled in the browser and show an error div instead of the body? ...

Unable to align span vertically using font-style "Luckiest Guy" in CSS

I have encountered an issue with vertically centering a span using the font-style "Luckiest Guy". https://i.sstatic.net/Lz8o3.png I attempted to use display: flex;align-items: center; on the span, but it did not work. App.vue <template> <div ...

Steps to update XmlHttpRequest URL during image upload

I am currently facing an issue with updating images on my website. When I try to update an image, it redirects to the wrong URL instead of the intended one. The form is set to post data to this URL: POST http://127.0.0.1/mgt/upload/processImage/foodImage ...

Enable Class exclusively on upward scrolling on the browser

Is there a way to dynamically change the class of an element only when the user scrolls the browser page upwards? Issue Filide>> JavaScript $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll <= 100) { ...

How to efficiently remove duplicate items from multiple select dropdowns in Angular using ng-repeat?

Need help with dynamically assigning objects to select boxes in AngularJS. I have a scenario where I add multiple select boxes to a form, but each box should only display items that haven't been selected in other boxes. How can I achieve this functio ...

Create a file with jQuery and send it to PHP

Hello everyone, I am currently in the process of developing a website that has the ability to generate an MS Excel file using jQuery and allow users to download it. My question is, how can I pass this generated file to PHP so that it can be sent as an atta ...

The functionality of ng-table appears to be compromised when working with JSON data

Currently, I am facing an issue while using a JSON file to populate data in my Angular ng-table. Even though the JSON data is being displayed in a regular table format, certain functionalities of ng-table like pagination and view limit are not functioning ...

Run JavaScript code when the HTML file has been modified for the second time

After browsing through this online forum, I stumbled upon a helpful solution. See the code snippet below for reference. However, I encountered a problem in my case. The script in question is essentially monitoring itself. The code resides in index.html an ...

Show the total of a JavaScript calculation in a designated input box

Is there a way to show the total sum of this calculation in an input field? function calculateSum1() { var sum = 0; //loop through each textbox and add their values $("input.miles").each(function() { //only add if the value is a number ...

Alter the Default Visibility on an HTML Page from Visible to Hidden with JavaScript

I found this code snippet on a website and made some modifications. On my webpage, I have implemented links that toggle the visibility of hidden text. The functionality is working fine, but the issue is that the hidden text is initially visible when the p ...