I have created a generic store for Products
in my web app. Naturally there are very many different types of products the website needs to display on different pages. So I have ended up with multiple states to represent each one. Here is my store:
const state = {
HomepageOffers:[],
Product: []
};
const getters = {
getHomepageOffers: (state) => state.HomepageOffers,
getProduct: (state) => state.Product
};
const actions = {
loadHomepageOffers({commit}) { // get all products to be featured on homepage
axios.get('/api/homepageoffers')
.then(response => {
commit('setHomepageOffers', response.data[0])
}).catch(function (error) {
console.log(error.response.data);
}
)
},
loadProduct(context, {ProductID}) { // gets a single product based on ProductID passed in URL
axios.get(`/api/${ProductID}`)
.then(response => {
context.commit('setProduct', response.data[0])
}).catch(function (error) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
)
}
};
const mutations = {
setHomepageOffers(state, HomepageOffers) {
state.HomepageOffers = HomepageOffers
},
setProduct(state, Product) {
state.Product = Product
}
};
export default {
state: state,
getters: getters,
actions: actions,
mutations: mutations
}
What is happening is that when a user goes to my /home
page, the HomepageOffers
state fills up with product data. Great.
When a user clicks on a particular product, the Product
state gets filled with a single product item and then the /Product.vue
component gets loaded in. Also great.
The only thing I noticed is that when a single product is fetched, the HomepageOffers
state is not emptied - it still has all the products in. I guess this is how its supposed to work, but my question is: Is it safe/best practice to only have one state per store or am I okay with having multiple states in a store?