I am encountering an issue with dispatching Actions from vuex. It's puzzling to me that ...mapActions is not initiating a request to Jsonplaceholder. However, using this.$store.dispatch
successfully retrieves all 10 users without any issues. Below are the scripts for 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");
}
}
});