i have an app in which i can view the list of products under category, each time i click the category to view a product it won't display until i hard refresh my browser before i get to display the list under the category
this is how i display the list of category in my navbar
<div
v-for="category in categories"
:key="category._id"
>
<router-link :to="`/categories/${category._id}`">
{{ category.type }}
</router-link>
</div>
this is my script tag to display the list of products the category.ID
<script>
import { mapActions } from "vuex";
import axios from "axios";
export default {
name: "Product",
components: {},
data() {
return {
category: {},
categories: [],
products: [],
catID: []
};
},
mounted() {
axios
.get(`https://taad.herokuapp.com/api/categories/${this.$route.params.id}`, {})
.then(response => {
console.log(response);
this.category = response.data.category;
})
.catch(error => {
console.log(error);
error;
});
axios
.get(`https://td.herokuapp.com/api/products`, {})
.then(response => {
console.log(response);
this.products = response.data.products;
const catID = this.category._id;
this.products = this.products.filter(
({ category }) => catID === category._id
);
})
.catch(error => {
error;
});
axios.get("https://td.herokuapp.com/api/categories").then(res => {
console.log(res);
this.categories = res.data.categories;
});
},
methods: {
...mapActions(["addProductToCart"]),
logout() {
localStorage.clear();
this.$router.push("/login");
}
}
};
</script>
if i click the a category from the navbar it takes me to the category.ID and display the product , but clicking another category when i'm on category.id page it changes the category.ID in my browser url , but wont update the product until i hard refresh it before it displays the product.
please what i'm i doing wrong
CodePudding user response:
I guess you need to use beforeRouteUpdate
and call the axios
part again.
From the documentation
beforeRouteUpdate(to, from) {
// called when the route that renders this component has changed, but this component is reused in the new route.
// For example, given a route with params `/users/:id`, when we navigate between `/users/1` and `/users/2`,
// the same `UserDetails` component instance will be reused, and this hook will be called when that happens.
// Because the component is mounted while this happens, the navigation guard has access to `this` component instance.
},