I can not for the life of me figure out why this isn't working so hoping you might be able to assist
All I am trying to do is a get request via a vuex store instead of in my component as I currently do as part of my learning vue/nuxt, but just can't get it to work as follows, can anyone see what I'm doing wrong please
vex store
import Vuex from "vuex";
import axios from "axios";
const URL = 'MYPATH';
const logStore = () => {
return new Vuex.Store({
state: {
logItems: {}
},
actions: {
setLog ({ commit }) {
axios
.get('URL')
.then(r => r.data)
.then(logItems => {
console.log(logItems) // I am getting back my results in log here
})
.then(logItems => {
commit('logItems', logItems)
})
},
},
mutations: {
logItems (state, logItems) {
state.logItems = logItems
},
getters: {
logItems(state) {
return state.logItems // log console here is empty object
}
},
});
};
export default logStore;
In my component I have
import { mapState } from 'vuex'
created () {
this.$store.dispatch('setLog', this.logItems)
console.log(this.$store.getters.logItems) // empty object here
},
Can anyone tell me why I am getting my results back to my action but not into my getter or component
Thanks
You'll need to return your logItems
here so the next then
has access to it
.then(logItems => {
console.log(logItems) // I am getting back my results in log here
return logItems;
})
When you use without curly braces, whatever you have in the function body is automatically returned, like you have here
.then(r => r.data)
However, when you do use curly braces, if you need the next function in the chain to get a value, you need to return it and get it in the next function
.then(logItems => {
console.log(logItems)
return logItems
})
.then(thisWillBeTheReturnAbove => { // ... code ... })
EDIT
As mentioned in the comments, I created a GitLab repository with an example that you can find here http://gitlab.com/vitorleite/vue-firebase-todo.
You should be able to clone it and run it locally by doing npm install
and npm run serve
, you'll need to change store.js
to include your Firebase endpoint. I did leave the one I used in a comment, but I'll change the permissions to be read-only
at some point.
I created the project using @vue/cli 3.0 and used the sample JsFiddle Vue Todo code as a base.