0

I am doing a fetch() request followed by then() function. I want to set the property of my component from inside the then() function. See below in the code this.h_editBut = true;. It is not updating the h_editBut property of the component. How to do this?

Vue.component('users-row', {
    props: ['row'],
    data: function() {
        return {
            h_editBut: false,
            fName: '',
            lName: '',
            userDetails: ''

        }
    },
    template: ` <li>
                    <div>{{row.id}}</div>
                    <div>{{row.fname}}</div>
                    <div>{{row.lname}}</div>
                    <div><button @click="fName=row.fname; lName=row.lname; editRow();" v-bind:class="{ishidden:h_editBut}">Edit</button></div>
                    <div v-if="h_editBut">
                        <input v-model="userDetails">
                    </div>
                </li>`,
    methods: {
        editRow: function() {


            fetch("http://localhost/pr2/web_service/users/details?fname=" + this.fName + "&lname=" + this.lName).then(function(response) {
                if (response.status !== 200) {
                    console.log('Looks like there was a problem. Status Code: ' +
                        response.status);
                    return;
                }

                return response.json();


            }).then(function(result) {

                this.h_editBut = true;


            }).catch(function(err) {
                console.log('Fetch Error :-S', err);
            });

        }
    }

});
Andrey
  • 4,020
  • 21
  • 35
russ
  • 103
  • 1
  • 7
  • 1
    You should use arrow functions -- `() => {}` -- for the `then()` callbacks to preserve the correct value of `this`. – Mark Dec 20 '18 at 14:39
  • 1
    @T.Dirks `then` calls can be chained. Check out https://javascript.info/promise-chaining to see how promise chaining works. – nbokmans Dec 20 '18 at 14:41
  • @nbokmans Oh, I never knew that... My bad, consider my comment deleted – T. Dirks Dec 20 '18 at 14:41
  • thanx, i got the answer here. https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback. i added var self = this; to wrapper funtion and now it works. – russ Dec 20 '18 at 15:00

0 Answers0