3

I am new to vue and working with vue 3 and the composition API. It is really hard to find stuff related to the composition API, so I try to get help here. I am using axios in combination with vuex modules for consuming APIs.

How can I transfere this code from options API to composition API?

TestApi.js

import axios from 'axios'
const posts = {
namespaced: true,
state: {
    posts: []
},
mutations: {
    SET_POSTS(state, data){
        state.posts = data
    }
},
actions: {
    loadPosts({commit}) {
        axios
            .get('https://jsonplaceholder.typicode.com/posts')
            .then( res => {
                commit('SET_POSTS', res.data)
            } )
            .catch(error => console.log(error))
    }
},
getters: {
    getPosts(state){
        return state.posts
    }
}
}
export default posts

App.vue

<template>
<div class="post" v-for="post in getPosts" :key="post.id">
    
      <h1>{{ post.title }}</h1>
      <p>{{ post.body }}</p>

  </div>
</template>

<script>

import { mapGetters } from 'vuex'
import { computed } from 'vue'


export default {
  computed: {
  ...mapGetters('posts', ['getPosts'])
  },
  created(){
  this.$store.dispatch('posts/loadPosts')
  }
}

</script>

<style>
  .post{
    margin-bottom: 20px;
  }
</style>

I tried something like this. But it does not work:

import { useStore } from 'vuex'
import { computed } from 'vue'

export default {
    setup(){
      getData();
      const store = useStore()
      function getData(){
        store.dispatch('posts/loadPosts');
      }
      const getPosts = computed(() => store.getters['getPosts'])
      return{ getPosts }
   }
}

Error: Uncaught (in promise) TypeError: Cannot read property 'dispatch' of undefined

1 Answer 1

1

You shoul run the function after initializing the store :

    setup(){
      
      const store = useStore()
       getData();
 ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.