Karlom
Karlom

Reputation: 14834

Uncaught (in promise) TypeError: Cannot set property of undefined with axios

I have this vue.js component that uses axios to retrive a json array of joke objects :

<template>
  <div id="show-jokes-all">
        <h2>Showing all jokes</h2>
        <div v-for="joke in jokes">
                <h2>{{joke.title}}</h2>
                <article>{{joke.body}}</article>
            <hr>
        </div>  

  </div>
</template>

<script>
import axios from 'axios';

    export default {
        name: 'showJokes',

      data () {
        return {
            jokes:[]

        }
      },

      methods: {

      },

      created() {
        axios.get('http://127.0.0.1:8090/api/jokes).then(function(data){    
       //console.log(data); works fine
        this.jokes = data.body;
        });
    }
}
</script>

When I log the result in console it's fine but when I try to put it in jokes array I get

Uncaught (in promise) TypeError: Cannot set property 'jokes' of undefined

This may be a trivial error but as a newbie to vue.js I'm stock on this so appreciate your hints.

Upvotes: 6

Views: 24341

Answers (2)

Jian Lan
Jian Lan

Reputation: 31

yes,you can use ES6 .

<template>
    <div id="show-jokes-all">
        <h2>Showing all jokes</h2>
        <div v-for="joke in jokes">
            <h2>{{joke.title}}</h2>
            <article>{{joke.body}}</article>
            <hr>
        </div>  
    </div>
</template>

<script>
import axios from 'axios';
  export default {
    name: 'showJokes',
    data () {
      return {
        jokes:[]
      }
    },
    methods: {
    },
    created() {
      axios.get('http://127.0.0.1:8090/api/jokes').then((data) => {    
      // console.log(data); // works fine
      this.jokes = data.body;
    });
  }
}
</script>

Upvotes: 3

Cholowao
Cholowao

Reputation: 967

You are out of this context. You should store this context on a variable.

 created() {
    let self = this
    axios.get('http://127.0.0.1:8090/api/jokes').then(function(data){    
   //console.log(data); works fine
    self.jokes = data.body;
    });
}

There are many ways in How to access the correct this inside a callback? . You can refer here for many ways.

thanks to Bert on comments

Upvotes: 18

Related Questions