I'm using a Vuex store to keep all the items in a shopping cart.
There's two actions on the store :
getCartContent, which gets called on page load (fetches the initial content from the backend, which in turn retrieves the data from the session)
addToCart, which is dispatched by the <Products> component when the user clicks the add to cart button.
Both of these call a respective mutation (with the same name), since you're not supposed to call mutations directly from within components.
Here is what the store looks like :
const store = new Vuex.Store({
state: {
items: [],
},
mutations: {
getCartContent(state, data){
axios.get('/api/cart').then(response => {
state.items = response.data;
});
},
addToCart(state, data){
axios.post('/api/cart/add', {
item_id: data.item,
});
}
},
actions: {
getCartContent(context){
context.commit('getCartContent');
},
addToCart(context, data){
context.commit('addToCart', {item: data.item});
}
}
});
This is working as expected, but now when an item is added to the cart (with a dispatch to the addToCart action from within the component), I would like it to call the getCartContent mutation just after so that it fetches a fresh list of items from the backend.
I tried commiting the second mutation from the same action, like this :
actions: {
// ...
addToCart(context, data){
context.commit('addToCart', {item: data.item});
context.commit('getCartContent');
}
}
But that doesn't always work, sometimes it will fetch the items but not always.
I also tried dispatching the getCartContent action from within the component itself, right after dispatching the addToCart action, but it's the same problem.
How can I solve this?
Your axios calls are asynchronous, meaning that your addToCart mutation might not necessarily be finished when your getCartContent mutation fires. So, it's not surprising that sometimes getCartContent doesn't return the items you told axios to send a post request for immediately prior.
You should move asynchronous calls to the vuex actions:
actions: {
getCartContent(context, data) {
axios.get('/api/cart').then(response => {
state.items = response.data;
context.commit('getCartContent', response.data),
});
},
addToCart(context, data) {
axios.post('/api/cart/add', {
item_id: data.item,
}).then(() => {
context.commit('addToCart', data.item)
})
},
}
And your mutations should do nothing but make simple, straight-forward changes to the module state:
mutations: {
getCartContent(state, items) {
state.items = items;
},
addToCart(state, item) {
state.items.push(item);
}
}
The above explanation assumes that instead of making a get('/api/cart') request after each POST request, you would just keep track of items by pushing the data to the state.items property.
If however, you really want to make the GET request after adding an item, you can just get rid of the addToCart mutation and dispatch the getCartContent action after the POST request finishes:
addToCart(context, data) {
axios.post('/api/cart/add', {
item_id: data.item,
}).then(() => {
context.dispatch('getCartContent');
})
},
Related
I want to trigger a function that GETs data from a http-server in a component, as soon as a button in a sibling component was pressed.
SignUpForm.vue has a button that triggers customSubmit()
customSubmit(){
//POST to API
const user = {
method: "POST",
headers: { "Content-Type": "application/json"},
body: JSON.stringify({newUser: this.newUser})
};
fetch("http://localhost:3080/api/user", user)
.then(response => response.json())
.then(data => console.log(data));
this.$emit('refresh', true)
this.clearForm();
}
The parent component looks as follows:
<template>
<div>
<SignUpForm #refresh="triggerRefresh($event)" />
<!-- <Exp /> -->
<Datatable :myRefresh="myRefresh" />
</div>
</template>
<script>
import SignUpForm from "./components/SignUpForm.vue";
import Datatable from "./components/Datatable.vue";
import Exp from "./components/exp copy.vue";
export default {
name: "App",
components: { Datatable, SignUpForm, Exp },
data() {
return {
myRefresh: false,
};
},
methods: {
triggerRefresh(bool) {
this.myRefresh = bool;
console.log(this.myRefresh);
},
},
};
</script>
Now i want the sibling component Datatable.vue
to fetch data from the server as soon, as this.$emit('refresh', true) is fired in SignUpForm.vue
Here's the script from Datatable.vue
export default {
data() {
return {
//Liste aller User
userData: null,
//temporärer User für das Details-Feld
printUser: [{ name: "", email: "", number: "" }],
//Property für den "read-Button"
showDetails: false,
//Property für den "Update-Button"
readOnly: true,
};
},
props: ["myRefresh"],
methods: {
pushFunction() {
fetch("http://localhost:3080/api/users")
.then((res) => res.json())
.then((data) => (this.userData = data));
},
readData(k) {
this.printUser.length = 0;
this.showDetails = true;
this.printUser.push(this.userData[k]);
},
editData(rowUser) {
if (!rowUser.readOnly) {
rowUser.readOnly = true;
const user = {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userData: this.userData }),
};
fetch("http://localhost:3080/api/users/patch", user)
.then((response) => response.json())
.then((data) => console.log(data));
} else {
rowUser.readOnly = false;
}
},
deleteData(k) {
fetch("http://localhost:3080/api/users/" + k, { method: "DELETE" }).catch(
(err) => console.log(err)
);
this.pushFunction();
},
//blaue Reihen
toggleHighlight(rowUser) {
if (rowUser.readOnly === false) {
return;
}
rowUser.isHighlight = !rowUser.isHighlight;
},
scrollDown() {
window.scrollTo(0, document.body.scrollHeight);
},
},
mounted() {
fetch("http://localhost:3080/api/users")
.then((res) => res.json())
.then((data) => (this.userData = data));
},
};
I really hope somebody can help a newbie out!
Two considerations, is it possible? and is it prudent?
Is it possible?
Yes, it is and you can implement it couple different ways.
Is it prudent?
No.
If you're going down this road, most likely the architecture is ineffective. In an ideal setup, your components should be responsible for managing the view only. That means what the user sees and collecting their input. The business logic should not live in the components. So if you have things like ajax calls and you put them into your component, you've coupled the logic to the view. One possible issue is that if the component is re-added for some reason, any in-progress ajax calls could be disrupted in an unexpected manner. While such scenarios can be handled, the bigger issue IMHO is that that when you are coupling business logic with the view layer you are creating an application that becomes increasingly difficult to reason about; This problem you have with sending event between sibling components is just one example.
Other options
The most common way, though not the only way, of dealing with this is by using a global store via Vuex.
Instead of initializing the Ajax request from your component, you call the Vuex action.
The action would usually set loading state either using single state variable (ie loadState=STATE.STARTED) or using isLoading=true, except instead of assigning the variable, vuex would do it through a mutation, so store.commit('setLoadState', STATE.LOADING). this will update the state in all components that are listening for changes in either the store directly or using a getter. Then the ajax request is made, and when it is done the store is updated again, either with store.commit('setLoadState', STATE.ERROR) or on success, store.commit('setLoadState', STATE.DONE) and store.commit('setUsers', response). Then your components only need to listen for changes, you can display a spinner if $store.loadState == STATE.LOADING
As long as the data for the subsequent call is related to data specific to the component (like specific user ID or name) you can handle the next call from the component. Instead of triggering the second API request from the component by watching for an event from the sibling, you can have the component watch the vuex store or data for a change. Then when $store.loadState becomes STATE.DONE, you can trigger another action for the other API call. I would only do this though if there is any part of the data that is specific to the API call, otherwise if the call comes right after in all circumstances, you might as-well call it as part of the same action
I am confused at why actions in Vuex can't just be handled within a component.
Assuming I have a basic store:
store.js
const initialState = () => ({
overlayText: ''
})
const mutations = {
setOverlayText: (state, payload) => {
state.overlayText = payload;
},
}
const actions = {
clearOverlay: (context, data) => {
return axios.get(data.url).then((response) => {
context.commit('setOverlayText', response);
});
},
}
If I want to make an API call and change data based off it like below using a Vuex Action:
Option 1
<button #click="dispatchClearOverlay">Get Data</button>
methods: {
clearOverlay() {
this.$store.dispatch('clearOverlay', {
url: '/api/clear-overlay',
})
}
}
what is the difference of just doing it within the component like this?
Option 2
<button #click="clearOverlay">Get Data</button>
methods: {
clearOverlay() {
axios.get('api/clear-overlay')
.then(resp => {
this.$store.commit('setOverlayText', response);
})
}
}
The examples you gave are slightly different in that in Option 1, the only possible value that will get stored in state.overlayText is the response from /api/clear-overlay. But in Option 2, you could pass any arbitrary text when you commit the mutation and that value would be stored in state.overlayText.
More generally, there are some important differences. Mutations have to be synchronous and Actions can be asynchronous. You can also fire multiple mutations by dispatching a single action (imagine if you frequently needed to call the same three mutations). These two features can help keep your components nice and lean, while centralizing more of the Store logic.
The Dispatching Actions section of the Actions docs helps illustrate these points.
I use vuex for my state as well as fetching data and display it in my application.
But I wonder if I'm doing it right. At the moment I dispatch an fetchDataAsync action from the component mounted hook, and I have an getter to display my data. Below is a code example of how I do it currently.
I wonder if it's necessary. What I really want is a getter, that looks at the state, checks if the data is already there and if the data is not there it is able to dispatch an action to fetch the missing data.
The API of vuex does not allow it so I need to put more logic into my components. E.g. if the data is depended of a prop I need a watcher that looks at the prop and dispatches the fetchDataAsync action.
For me it just feels wrong and I wonder if there is a better way.
let store = new Vuex.Store({
state: {
posts: {}
},
mutations: {
addPost(state, post) {
Vue.set(state.posts, post.id, post);
}
},
actions: {
fetchPostAsync({ commit }, parameter) {
setTimeout(
() =>
commit("addPost", { id: parameter, message: "got loaded asynchronous" }),
1000
);
}
},
getters: {
// is it somehow possible to detect: ob boy, I don't have this id,
// I'd better dispatch an action trying to fetch it...?
getPostById: (state) => (id) => state.posts[id]
}
});
new Vue({
el: "#app",
store,
template : "<div>{{ postToDisplay ? postToDisplay.message : 'loading...' }} </div>",
data() {
return {
parameter: "a"
};
},
computed: {
...Vuex.mapGetters(["getPostById"]),
postToDisplay() {
return this.getPostById(this.parameter);
}
},
methods: {
...Vuex.mapActions(["fetchPostAsync"])
},
mounted() {
this.fetchPostAsync(this.parameter);
}
});
I also created a codepen
Personally I think the solution you suggested (adding a watcher that dispatches fetchPostAsync if the post is not found) is the best one. As another commenter stated, getters should not have side effects.
here is my setup. The state "categories" in the state is fetched async from a json endpoint.
In the component I want to work with this data, but if I reload the page the categories are always empty.
methods: {
onSubmit() {
console.log(this.filter);
},
formCats(items) {
console.log(items);
// const arr = flatten(data);
// console.log(arr);
}
},
created() {
const data = this.categories;
this.formCats(data);
},
computed: {
...mapState(['categories'])
}
I also tried async created() with await this.categories. Also not working as expected! Would be great if someone could help me with this. Thanks!
This is happening because the async fetch doesn't finish until after the component is already loaded. There are multiple ways to handle this, here's one. Remove created and turn formCats method into a computed.
computed: {
...mapState(['categories']),
formCats() {
let formCats = [];
if (this.categories && this.categories.length) {
formCats = flatten(this.categories);
}
return formCats;
}
}
formCats will be an empty array at first, and then it will immediately become your formatted categories when this.categories is finished fetching.
I want to display a loading effect in a vue template whilst an asynchronous action in vuex is still running. But the loading effect doesn't seem to work. How do I fix it?. Is there any better way I can achieve this?
This is how I defined the action:
actions: {
signIn({ state }, user) {
auth()
.signInWithEmailAndPassword(userInfo.email, userInfo.password)
.then(result => {
return result
})
},
},
This how defined the dispatch in vue template method:
let loader = this.$loader.show()
this.$store.dispatch('signIn', this.user).then(() => {
loader.hide()
})
I expected the loader to start when the action begins and end when the action ends but it starts and ends almost instantly.
Just add return statement, that returns a Promise so you can then it in your component.
actions: {
signIn({ state }, user) {
return auth()
.signInWithEmailAndPassword(userInfo.email, userInfo.password)
.then(result => {
return result
})
},
},