1

I hope you can help me with this. I am trying to dynamically display some buttons according to an API call. I just dont happen to manage to receive the data before the page renders.

new Vue({
        el: '#app',
        data : function(){
            return{
                results : [],
            }
        },

        beforeCreate : function(){
                    axios.get('somesite')
                      .then(function (response) {
                        this.results =  response.data;
                        console.log(this.results);
                      })
                      .catch(function (error) {
                        console.log(error);
              }); 
          },
})

and the html is:

<html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no">
            <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">

    </head>
    <body>
        {% raw %}
        <div class="container">
            <div id="app">
                <div class="response_list">
                    <button class="entries" v-for="entry in results"></button>
                </div>
            </div>
        </div>
        {% endraw %}
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script type="text/javascript"  src="{{ url_for('static', filename='js/index.js') }}"></script>

        </body>
</html>
Satyam Pathak
  • 6,612
  • 3
  • 25
  • 52
user2419831
  • 181
  • 4
  • 11

1 Answers1

0

It appears you aren't binding to the context of the beforeCreate method in your axios promise functions.

By using the forward arrow function to bind the context of your component to the axios promise function you will be able to update the component data object properly:

beforeCreate : function(){
  axios.get('/')
    .then((response) => {
      this.results =  response.data
      console.log(this.results)
    })
    .catch((error) => {
      console.log(error)
    });
},
Nijikokun
  • 1,514
  • 1
  • 15
  • 22