1

I have a getter where all products are stored there, and when I want to get only one product dynamically depending on this.$route.params.id it doesn't return any value

this code works correctly when I navigate to a certain product, but when I refresh the page I lose everything

computed: {
        ...mapGetters(["getAllProducts"]),
        product() {
            return this.getAllProducts.filter(item => {
                return  item.id === this.$route.params.id;
            });
        }
    }

But if I supplied filter() with static value in instead of this.$route.params.id like below it works

        product() {
            return this.getAllProducts.filter(item => {
                return  item.id === 1;
            });
        }

I really don't know what is the problem, despite of in another component in my project I did some filters on some computed properties and it worked

update: the routes config

{
    path: "/product/:id",
    name: "product-page",
    component: ProductPage,
    props: true
}
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
MR Loll
  • 31
  • 10

3 Answers3

3

Route params are usually parsed as strings. Try converting the route param value to number type and then do the match:

product() {
    return this.getAllProducts
      .filter(item => item.id === Number(this.$route.params.id));
}
Towkir
  • 3,889
  • 2
  • 22
  • 41
  • You shouldn't *parse* the number. You should only convert its type. In other words, you should use `Number(x)` rather than `parseInt(x, 10)`. Also note `+x` is equivalent to using `Number(x)` - they basically use the same code, under the hood. – tao Mar 17 '21 at 20:41
1

According to the official docs :

When props is set to true, the route.params will be set as the component props

so add the id to your props like then use it instead of this.$route.params.id :

props:['id'], //refers to this.$route.params.id
...
computed: {
        ...mapGetters(["getAllProducts"]),
        product() {
            return this.getAllProducts.filter(item => {
                return  item.id == this.id;
            });
        }
    }
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
0

Try giving this.$route.params.id as a computed propertly. Then call it in the filter method.

computed: {
    ...mapGetters(["getAllProducts"]),
    routerId() {
     return this.$route.params.id;
    },
    product() {
        return this.getAllProducts.filter(item => {
            return  item.id === this.routerId;
        });
    }
}
mathu mitha
  • 306
  • 2
  • 6