vue3 app problem to access state’s variables in store file

I am trying to update in my store (index.js)file the array posts
but I get this error
enter image description here
Here the files

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

createApp(App).use(store).use(router).mount('#app')

index.js


import { createStore } from 'vuex'
import { baseApiURL } from '@/config/env'
import axios from 'axios'



const store = createStore({
  state() {
      posts: [{}],
    }
  },
  // GETTERS
  getters: {
    // GET TOTAL PRODUCT ARRAY
    getPosts: (state) => {
      return state.posts
    },
    // GET TOTAL POSTS NUMBER
    getTotalPosts: (state) => {
      //console.log('This is the total post!' + this.totalPosts)
      return state.totalPosts
    },

  },
  // MUTATIONS
  mutations: {
    setCurrentPost(state, newPost) {
      state.currentPost = newPost
      console.log('product mutation -->    ' + state.currentPost.title)
    }
  },
  // ACTIONS
  actions: {
  
    actionLoadListPosts: (context, info) => {
      console.log(info)
      console.log(context)
      axios
        .get(`${baseApiURL}/blog/${info.page}/${info.recordsPerPage}`, {
          headers: {
            Authorization: 'System b24b3b0e-9257-466b-949e-8c0c3841eeb5'
          }
        })
        .then((response) => {
          info.showLoader = false
          console.log(response.data.posts)
          state.posts = response.data.posts  //<<<<<------- error ?????
          console.log(this.posts)
          // return true
        })
    }
    
  }
})
export default store


Please any edea about it? I am new with Vue3. Thanks.

I try to use a mutation for it but it doesn’t seem very logical since I am already inside the store…and I get error as well.
I used the same approach with another vue2 app and the access was completely fine.

  • You could do context.state.posts = response.data.posts; – however, read this as to why you should use a mutation

    – 

Leave a Comment