skip to Main Content

I try to fetch data from a mySQL database using Axios to set the initial values of a form input generated with vue.js-formulate.

Here is my script where I want to set the initial value of "question1":

new Vue({
            el: '#app',
            created() {
                this.fetchData();
            },
            

            data: {
                row: "",
                values: {
                    question1: this.row["answerq1"],
                }
            },
            methods: {
                fetchData() {
                    axios.get('retrieve.php')
                        .then(function (response) {
                            this.row = response.data;
                            // Checking output in Console:
                            console.log(this.row["answerq1"]);
                            
                        });
                },
}
})

The fetchData() function is working as expected, this.row["answerq1"] prints the expected string. However, access this value in the data part produces the error "this.row is undefined". I’m guessing it has something to do with the lifecycle of the created() hook but I can’t figure it out.

2

Answers


  1. Chosen as BEST ANSWER

    I have found the answer to my question for anyone encountering a similar problem:

    new Vue({
        el: '#app',
        created() {
            this.fetchData();
        },
        
    
        data: {
            row: [],
            values: {
                question1: null
            }
        },
    
        
        methods: {
            fetchData() {
                axios.get('retrieve.php')
                    .then((response) => {
                        this.row = response.data;
                        
                        this.values.question1 = this.row["answerq1"];
                
                    });
            },
        }
    })
    

  2. this.row is an empty string before the API request is done, therefore you cannot access this.row["answerq1"]. You need to wait for the API request to finish.

    Make this change and it should work:

    data() {
      return {
        row: "",
        values: {
          question1: "" // set to empty string
        }
      };
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search