Search code examples
vuejs3vue-composition-apicomputed-properties

How to get value from computed properties?


I am using compostion api in my state management(store.js) that return state addtocalender. Then i make variabel addtocalender using computed properties that return getAddtocalender method that i declare in my state management, but when i want to get addtocalender value in component.app that i want to put in config variabel it never return the value.

I try to run console.log(addtocalender.vale.name and the result is undefined.

How to get addtocalender value?

store.js

import { reactive, readonly } from 'vue';
import axios from 'axios';

const state = reactive({
    addtocalender: [],
});

const mutations = {
    updateAddtocalender: (payload) => state.addtocalender = payload,
}

const actions = {
    getAddtocalender: () => {
      return axios.get('http://localhost:3000/addtocalender').then((response) => {
        mutations.updateAddtocalender(response.data);
      });
    },
};

export default {
  state: readonly(state),
  mutations,
  actions
};

component.vue

<script setup>
import { onMounted, ref, inject, computed, watchEffect } from "vue";

const store = inject('store');

const addtocalender = computed(() => store.state.addtocalender);

store.actions.getAddtocalender();

const config ={
    # i want to put addtocalender value here
    name: addtocalender.value.name,
    startDate: addtocalender.value.startDate,
};

</script>

addtocalender.json

{
    "name":"Reminder to star the add-to-calendar-button repo",
    "description":"Check out the maybe easiest way to include add-to-calendar-buttons to your website:\n→ [url]https://github.com/jekuer/add-to-calendar-button|Click here![/url]",
    "startDate":"2022-08-14",
    "location":"World Wide Web",
    "label":"Simpan ke kalender!",
    "startTime":"10:13",
    "endTime":"12:57",
    "options":[
        "Google",
        "Apple",
        "iCal",
        "Yahoo",
        "Outlook.com",
        "Microsoft365"
    ],
    "timeZone":"Asia/Jakarta",
    "trigger":"click",
    "iCalFileName":"Reminder-Event"
}

Solution

  • Solved..

    I use await,, this is the improvement of my code.

    <script setup>
    import { onMounted, ref, inject, computed, watchEffect } from "vue";
    
    const store = inject('store');
    
    const addtocalender = computed(() => store.state.addtocalender);
    
    # use here
    await store.actions.getAddtocalender();
    
    const config ={
        # i want to put addtocalender value here
        name: addtocalender.value.name,
        startDate: addtocalender.value.startDate,
    };
    
    </script>