-3

I am trying to transfer the result of a response to a characters object, but it throws an error:

Cannot read property 'characters' of undefined

<script>
const axios = require("axios");
export default {
  data: () => ({
    characters:[],
  }),
  created() {
    axios
      .get("https://rickandmortyapi.com/api/character")
      .then(function(response) {
        const resp = response.data.results;
        this.characters.push(resp);
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      });
    
  },
};
</script>
Philip Raath
  • 460
  • 3
  • 18
  • Hang on … there's no `characters` property on the object at all, only one you generate on demand when the `data` method is called. – Quentin Sep 28 '20 at 21:33
  • `characters` is defined in the body of another function. What exactly are you trying to achieve? – Guerric P Sep 28 '20 at 21:34

1 Answers1

0

this is not referring to your vue instance, so there are some ways to fix it

Solution 1 arrow function

    axios
      .get("https://rickandmortyapi.com/api/character")
      .then(response => {
        const resp = response.data.results;
        this.characters.push(resp);
      })
      .catch(error => {
        // handle error
        console.log(error);
      });

Or bind

    axios
      .get("https://rickandmortyapi.com/api/character")
      .then(function(response) {
        const resp = response.data.results;
        this.characters.push(resp);
      }.bind(this))
      .catch(function(error) {
        // handle error
        console.log(error);
      }.bind(this));

Or you choose async / await

async created() {
  try {
     let { data } = await axios.get("https://rickandmortyapi.com/api/character")
     this.characters.push(data.results);
  } catch(err) {
     console.log(err)
  }
},
bill.gates
  • 14,145
  • 3
  • 19
  • 47