1

I am trying to filter a list of posts using the userId in checkboxes. I am pulling the data from: https://jsonplaceholder.typicode.com/posts and want to then add checkboxes that when checked filter the list by userId. This is what I have currently:

var app = new Vue({
  el: '#app',
  data() {
    return {
      jobs: [],
      userIds: ['1', '2', '3'],
      checkedUserIds: []
    }
  },
  created() {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then(response => (this.jobs = response.data))
  },
  computed: {
    filteredJobs() {
      if (!this.checkedUserIds.length)
        return this.jobs
      return this.jobs.filter(job => this.checkedUserIds.includes(job.userId))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">

  <div v-for="userId in userIds">
    <input type="checkbox" v-model="checkedUserIds" v-bind:value="userId" /> {{userId}}
  </div>

  <div v-for="job in filteredJobs">
    <h2>{{ job.title }}</h2>
    <div>{{ job.body }}</div>
  </div>
</div>

I am stumped on why when I click a checkbox the whole list disappears instead of filtering by the userId

1 Answer 1

3

Your userIds: ['1', '2', '3'], is an array of strings not integers. Try userIds: [1, 2, 3],

The json file has userId as integers. Types to need to be the same for this function to work.

var app = new Vue({
  el: '#app',
  data() {
    return {
      jobs: [],
      userIds: [1,2,3],
      checkedUserIds: []
    }
  },
  created() {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then(response => (this.jobs = response.data))
  },
  computed: {
    filteredJobs() {
      if (!this.checkedUserIds.length)
        return this.jobs
      return this.jobs.filter(job => this.checkedUserIds.includes(job.userId))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">

  <div v-for="userId in userIds">
    <input type="checkbox" v-model="checkedUserIds" v-bind:value="userId" /> {{userId}}
  </div>

  <div v-for="job in filteredJobs">
    <h2>{{ job.title }}</h2>
    <div>{{ job.body }}</div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Such I stupid mistake on my part... Thank you for the help!
@user9664977 Not a problem. Programming languages are becoming more type strict (which is good for less runtime errors)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.