1

I'm fetching data from api using axios, when I console.log(app.books) I can see my data but it won't display on the page. I'm using v-for to display the data on a table. I'm confused what went wrong in my code?

<tbody>
  <tr v-for="book in books" class="text-center">
    <td> {{ book.id }} </td>
    <td><a href="#"> {{ book.name }} </a></td>
    <td> {{ book.author }} </td>
    <td> ${{ book.price}} </td>
    <td>
      <a href="#" class="text-success" @click="showEditModal=true">
        <i class="fas fa-edit"></i> 
      </a>
    </td>
    <td>
        <a href="#" class="text-danger" @click="showDeleteModal=true">
          <i class="fas fa-trash"></i>  
      </a>
    </td>
  </tr>
</tbody>

export default {
  name: "App",
  data: function() {
    return {
      successMsg: false,
      errorMsg: false,
      showAddModal: false,
      showEditModal: false,
      showDeleteModal: false,
      books: [],
      newBook: {name: "", author: "", price: ""},
      currentBook: {}
    }
  },
  mounted: function(){
    this.getAllBooks();
  },
  methods: {
    getAllBooks: function(){
      axios.get('http://localhost/crud-vuejs/src/Backend/api.php?action=read')
     .then(function(res) {
        if(res.data.error){
          app.errorMsg = res.data.message;
        }
        else{
          app.books = res.data.books;
        }
        console.log(app.books);
     });
    }
  }
}

Response Payload:

{"books":[{"id":"1","name":"Harry Potter","author":"J. K. Rowling","price":"40"},{"id":"2","name":"The great gastby","author":"Scott Fitzgerald","price":"36"},{"id":"3","name":"To Kill a Mockingbird","author":"Harper Lee","price":"26"}]}

1 Answer 1

1

You should replace app with this

export default {
  name: "App",
  data: function() {
    return {
      successMsg: false,
      errorMsg: false,
      showAddModal: false,
      showEditModal: false,
      showDeleteModal: false,
      books: [],
      newBook: {name: "", author: "", price: ""},
      currentBook: {}
    }
  },
  mounted: function(){
    this.getAllBooks();
  },
  methods: {
    getAllBooks: function(){
      axios.get('http://localhost/crud-vuejs/src/Backend/api.php?action=read')
     .then((res) => {
        if(res.data.error){
          this.errorMsg = res.data.message;
        }
        else{
          this.books = res.data.books;
        }
        console.log(this.books);
     });
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

i did replace it but then i got an error " this is undefined "
Yes you are right. I updated the answer. In the then promise block you were creating a new local function scope. I replaced it with a fat arrow function and now it should work. (res) => { ... }
so it's all about the arrow function

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.