Reputation: 56
I got a problem with dispatching Actions from vuex, I don't know why, but ...mapActions do not trigger request to Jsonplaceholder. However this.$store.dispatch
return all 10 users without any problems, so here is scripts of two files, home.vue page, and store.js:
HOME:
<script>
import { mapGetters, mapActions } from "vuex";
export default {
name: "Home",
created() {
// this.$store.dispatch('fetchUsers')
console.log(this.$store);
},
computed: {
...mapGetters(["getUsers"])
},
methods: {
...mapActions(["fetchUsers"]),
increment() {
this.$store.commit("increment");
console.log(this.$store.state.count);
}
}
};
</script>
STORE:
const store = new Vuex.Store({
state: {
count: 0,
users: []
},
getters: {
getUsers(state) {
return state.users;
}
},
mutations: {
increment(state) {
state.count++;
},
setUsers(state, users) {
console.log(state, users);
state.users = users;
}
},
actions: {
fetchUsers({ commit }) {
return new Promise(resolve => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => {
return response.json();
})
.then(result => {
console.log(result);
commit("setUsers", result);
return resolve;
})
.catch(error => {
console.log(error.statusText);
});
});
},
incrementUsers({ commit }) {
commit("fetchUsers");
}
}
});
Upvotes: 1
Views: 1453
Reputation: 16513
As you are using mapGetters
and mapActions
here:
import {mapGetters, mapActions} from 'vuex'
the easier way to do this is:
created() {
this.fetchUsers()
console.log(this.getUsers)
},
computed: {
...mapGetters(['getUsers'])
},
methods: {
...mapActions(['fetchUsers']),
}
Also, just in case if you like to use name-spacing then follow this answer: https://stackoverflow.com/a/55269592/1292050
Upvotes: 1