Prashant Bhardwaj
Prashant Bhardwaj

Reputation: 176

data in Vue instance doesn't get updated after axios post response

I am writing a code piece to submit the html form data on a POST REST API. Using Vue.js and axios for that.

My Vue.js code is like this -

const app = new Vue({
    el: "#main-div",
    data() { return {
        name: 'Please enter the name',
        showEdit: true,
        showResponse: true,
        responseText: null
    }
    },
    methods: {
         savePerson: function () {
           this.showEdit = false;
           axios
            .post('/api/person', {
                name: this.name
              })
              .then(function (response) {
                this.responseText = response.data.name+ ' added successfully.';
                console.log(response);
                console.log(response.data.name+ ' added successfully.');
              })
              .catch(function (error) {
                this.responseText = error.message;
                console.log(error);
              });
         }
    }
}

)

And html -

<div id="main-div">
<h2> Fill out the details to create a Person</h2>
<div v-if="showEdit">
    <form >
        <div>
            Name: <input v-bind:value = 'name' type="text" v-on:focus="name= ''" />
        </div>
        
        <div>
            <button v-on:click="savePerson">Save</button>
        </div>
    </form>
</div>
<div v-if="showResponse">
    <div><p>{{ responseText }}</p></div>
    <div>
        <button v-on:click="showEdit = true">Add one more person</button>
    </div>
</div>

This code doesn't update responseText. That I can check in Vue plugin in browser. Any idea what is not correct in my example?

Upvotes: 0

Views: 1029

Answers (2)

Abdallah M-uhammeed
Abdallah M-uhammeed

Reputation: 1

to bind data with the input field you need to use v-model in the HTML and try to use the arrow function in the API call.

Upvotes: 0

Dan
Dan

Reputation: 63059

You need to use an arrow function in the callback or else the function injects its own this context:

.then((response) => {
...
})
.catch((error) => {
...
})

Or you could use async/await:

async savePerson() {
  this.showEdit = false;
  try {
    const response = await axios.post('/api/person', {
      name: this.name
    })
    this.responseText = response.data.name+ ' added successfully.';
  } catch(error) {
    this.responseText = error.message;
  }
}

Upvotes: 1

Related Questions