Search code examples
javascriptajaxvue.jsvue-resource

How to apply a filter on an ajax repeated list using Vue.js?


I'm trying to apply a filter on a list which I retrieve using AJAX, the problem I have is that Vue.js tries to apply the filter before the list is loaded and shown.

This is what I have so far:

<template>
  <div class="grid__container games">
    <h2>Games</h2>
    <div v-if="games">
      <table>
        <tr>
          <th>Player One</th>
          <th>Results</th>
          <th>Player Two</th>
          <th>Played At</th>
        </tr>
        <tr v-for="game in games.data">
          <td>{{ game.player_one }}</td>
          <td>{{ game.player_one_goals }} - {{ game.player_two_goals }}</td>
          <td>{{ game.player_two }}</td>
          <td>{{ [ game.created_at, "YYYY-MM-DD h:mm:ss" ] | moment "dddd, MMMMM, Do YYYYY" }}</td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
  import auth from '../auth'

  export default {
    data() {
      return {
        data: '',
        games: ''
      }
    },
    methods: {
      getGames() {
        this.$http
          .get('/api/games', { headers: auth.getAuthHeader() }).then((data) => {
            this.data = data
            this.games = JSON.parse(this.data.body)
        }, (error) => {
          console.log(error)
        })
      }
    },
    created: function () {
      this.getGames()
    } 
  }
</script>

Here I am trying to apply the filter on the game's created at date, it ends throwing an error instead when trying to load the page

Uncaught ReferenceError: string is not defined

Is there a way to make the filter 'wait' for the list to be loaded before trying to filter the data?


Solution

  • The quickest thing you can do is use a method instead of a filter:

    createdDate(game) {
      if (game !== undefined && game.date !== undefined) {
        return someFunctionThatWillFormatYourDate(game.date)
      } else {
        return ''
      }
    }