Best practices for effectively implementing Vuex getters within the Nuxt Vue Composition API

I have been using @nuxtjs/composition-api(0.15.1), but I encountered some issues when trying to access Vuex getters within computed().

Below is the code snippet using composition API:

import { computed, useContext, useFetch, reactive } from '@nuxtjs/composition-api';

  setup() {
    const { store } = useContext();
    const products = computed(() => {
      return store.getters['products/pageProducts'];
    });
    const pagination = computed(() => {
      return store.getters['products/pagination'];
    });

    useFetch(() => {
      if (!process.server) {
        store.dispatch('products/getPage');
      }
    });

    return {
      products,
      pagination,
    };
  }

The console consistently displays this warning message:

[Vue warn]: Write operation failed: computed value is readonly.

found in

---> <Pages/products/Cat.vue> at pages/products/_cat.vue
       <Nuxt>
         <Layouts/default.vue> at layouts/default.vue
           <Root>

This situation has left me perplexed. I did not attempt to modify the computed property; rather, I fetched the data via AJAX and then simply assigned it to the state within Vuex mutations.

However, when I refactored the code using option API as shown below:

export default {
  components: {
    ProductCard,
    Pagination,
  },
  async fetch() {
    if (process.server) {
      await this.$store.dispatch('products/getPage');
    }
  },
  computed: {
    products() {
      return this.$store.getters['products/pageProducts'];
    },
    pagination() {
      return this.$store.getters['products/pagination'];
    },
  },
};

Everything functioned smoothly without any errors or warnings. Could it be that I am incorrectly accessing the getters in the composition API, or is this potentially a bug within the @nuxtjs/composition-api plugin?

Answer №1

Solution for Issue #207: Fixing computed property hydration issue with useFetch

It seems like this problem may persist until the release of Nuxt3.

However, I have discovered a workaround using the middleware() function instead of useFetch(). This solution involves fetching AJAX data with Vuex Actions and retrieving it via Getters using computed().

Below is an illustrative example that tackles the same scenario as mentioned in the previous question:

~/pages/index.vue :

<script>
import { computed, onMounted, useContext, useFetch } from '@nuxtjs/composition-api';

export default {
  async middleware({ store }) {
    await store.dispatch('getUser');
  },
  setup() {
    const { store } = useContext();
    const user = computed(() => store.getters.user);

    return {
      user,
    };
  },
}
</script>

~/store/index.js (Vuex)

const state = () => ({
  user: {},
});

const actions = {
  async getUser({ commit }) {
    const { data } = await this.$axios.get('https://randomuser.me/api/');
    console.log(data.results[0]);
    commit('SET_USER', data.results[0]);
  },
};

const mutations = {
  SET_USER(state, user) {
    state.user = user;
  },
};

const getters = {
  user(state) {
    return state.user;
  },
};

If you notice any issues with this approach, please share your feedback and suggestions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the total amount within a specified date range when retrieved as JSON?

Consider the following JSON structure: { "timesheets": [ { "user": { "username": "erik", "first_name": "Erik", }, &q ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

Utilizing Vue.js keep-alive to optimize performance by excluding Ionic components

The components from a specific library are not compatible with Vue.js' keep-alive feature. I have attempted to exclude them using exclude="/^ion-*./", but it has not been successful. These components do not have a designated name. Is there a way to p ...

Explore vue3 components using vue-test-library and universal components

I started creating unit tests for a production app using jest, @testing-library/vue, and supporting libraries. The first test I created is as follows: import vue from "vue"; import { render } from "@testing-library/vue"; import LibBtn f ...

Looping through a dynamic array in Vue.js

I am working with two arrays: days:[0,1,2,3,4,5,6] and wdays:[2,3,6] My goal is to iterate through both arrays and display the output as follows: 0 : not present 1 : not present 2 : present 3 : present 4 : not present etc... The implementation should be ...

How can I retrieve the `checked` state of an input in Vue 3 using Typescript?

In my current project, I am using the latest version of Vue (Vue 3) and TypeScript 4.4. I am facing an issue where I need to retrieve the value of a checkbox without resorting to (event.target as any).checked. Are there any alternative methods in Vue tha ...

Is there a way for me to showcase the latitude and longitude retrieved from JSON data on a Google Map using modals for each search result in Vue.js?

After receiving JSON data with search results, each containing latitude and longitude coordinates, I am attempting to display markers on a Google map modal when clicking "View Map". However, the code I'm using is not producing the desired outcome. Th ...

ERESOLVE encountered issues resolving the dependency tree for a project using .NET Core 3.1 and Vue.js framework

I encountered an issue while trying to build my application. The error message is as follows: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class ...

Retrieve JSON object based on its unique identifier from a different JSON file

I am working with 2 API resources: and it returns JSON data like this: { "id": 771, "title": "Call to Alyce Herman - Engine Assembler", "assigned_with_person_id": 317, } provides ...

Discovering the automatically generated routes in Nuxtjs

Can I access the route list created by Nuxt.js based on pages folder items? The issue is that I am unsure of the exact route name generated for each component. $router.push({name: 'no-idea-what-the-route-name-is', query: { id: data.id } }) This ...

Enable the normal back button functionality when new query parameters are added dynamically

Whenever a page is visited without any parameters, I push some parameters to the Nuxt router. This process can be seen in more detail at https://router.vuejs.org/guide/essentials/navigation.html. For example, if someone visits: /program, they will end up ...

Exploring the magic of Plugins within Vue's Single File Components

One of my recent projects involved writing a custom plugin in Vue: var MyCoolVuePlugin = { install(Vue) { Vue.prototype.doStuff = function() { console.log("I'm a useless plugin") } } } export default MyCoolVuePlug ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...

Utilizing Vue.js 2.x to send a REST API request with a collection of objects

I currently have an array of objects stored in state, and my goal is to send this entire structure to a back end API for processing and receive a new set of values in return. Below is a simplified representation of this structure as viewed in the develope ...

Vue-good-table does not show the "empty state" once it has been populated with data

I am facing an issue with my vue-good-table where it does not re-render to display the "emptystate" message when I set the rows field to an empty array. Initially, it shows the message before I assign values into the rows field and then correctly displays ...

The pencil-drawn pixel on the canvas is positioned off-center

Currently, I am using p5.js to draw pixels on canvas with a pencil tool. However, I have encountered an issue where the pixel does not appear centered when the size of the pencil is set to 1 or smaller. It seems to be offset towards the left or right. Upo ...

How can I retrieve the locale for dateTimeLocalization in Vue i18n?

Currently, I am using a tutorial on implementing i18n in my vue code. It is working well with just one inconvenience - the language is hard-coded. Here is how my Localization file looks: export default: { 'fr-fr': { ... }, &ap ...

combining vue.js component with a laravel blade template

Has anyone tried using Laravel Blade in a <template></template> section of a Vue/Vueify component? I'm struggling to figure out how to make the Blade processor work and have it output the HTML code into the template within the .vue file or ...

I'm encountering an issue with my function in Vuejs where it is only going through one loop before breaking out. How can I

I'm attempting to validate all items in the cart and disable the sell button if the item is already in the cart (I have this implemented for other functionalities). It seems like my loop is only iterating once before stopping. Any suggestions on how I ...