4

I'm practicing using axios with Vue, but I think this may be more of a general JSON question.

I've successfully used axios to get my local products.json file and I'm then using filter to create a new array that only has products that have a matching department property, and looping those out.

Is this the correct way of doing this, or can I actually filter the JSON result on the original axios call? I understand I can to pass a parameter which will in turn perform a specific database call, and only provide the required JSON in the first place.

data(){
    return {
        products: []
    }
},
components: {
    Product
},
computed: {
    foodProducts(){
        return this.products.filter(x => x.department == 'Food')
    }
},
mounted() {
    axios
    .get('./json/products.json')
    .then(response => (this.products = response.data.products))
}

Thanks. Just trying to clarify the theory behind it.

2
  • 1
    So, what's wrong?
    – vahdet
    Commented Dec 27, 2018 at 18:26
  • Nothing, just wanted to clarify this is the right way to do it. As in, can I filter the result on the initial axios call, or will I always need to filter it afterwards as a computed property? Commented Dec 27, 2018 at 18:27

2 Answers 2

5

It works in many ways depending on your situation or requirement.

Your way works. Alternatively, you can also filter the result directly from the API call assuming that the backend is returning a full result.

data() {
 return {
  filteredProducts: []
 }
}

mounted() {
 axios.get(API_URL)
  .then(response => {
   const products = response.data

   this.filteredProducts = products.filter(product => product.department.includes('food'))
  })
}
2

If you're querying the products list from a Back-end server, you may use query parameters like

xxx/products?department=XXX

then the backend server can do the filtering for you.

In your case, it looks like you are simply reading a local JSON file, so the entire JSON is returned, and you have to filter yourself.

2
  • This only works if you have full control of the backend as well, but it still works given the circumstances. Commented Dec 27, 2018 at 19:19
  • 1
    yes of course. Check the API docs if you're using a public API endpoint or check with back-end developer on passing query string parameters. @RuChernChong thanks for pointing out.
    – Tang Yun
    Commented Dec 27, 2018 at 19:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.