Issue with Vuex not functioning properly in Nuxt.js

I'm facing an issue with setting the state in Vuex on my Nuxt.js App. It seems to not be working correctly. So, here is how I am trying to set the state using the fetch method:

fetch({app, store, route}) {
    app.$axios.$get(`apps/${route.params.id}`)
      .then(res => {
        store.dispatch('setApp', {
          ...res,
          id: route.params.id
        })
        console.log(app.store.state.app);
      })
  }

Everything works fine here when I log 'app.store' - the data is present. However, when I try to log it in:

  created() {
    console.log(this.$store);
  },
  mounted() {
    console.log(this.$store);
  }

Below is my store code:

const store = () => new Vuex.Store({

  state: {
    app: ''
  },
  mutations: {
    'SET_APP' (state, payload) {
      state.app = payload
    }
  },
  actions: {
    setApp (ctx, payload) {
      ctx.commit('SET_APP', payload)
    }
  },
  getters: {

  }
})

The state appears to be empty and as a result, the data is not rendering on my template. I would appreciate any help!

P.S: The logging works fine on the client-side, but not on SSR.

Answer №1

According to the information provided in the documentation

If you want the fetch method to be asynchronous, you need to return a Promise. Nuxt.js will then wait for this promise to be resolved before rendering the component.

In the code example above, an axios request is made within the fetch hook. However, since no promise is returned, Nuxt does not wait for it to resolve. As a result, it continues to render the component, executing the created and mounted hooks without the $store being populated at that time.

To address this issue, you should ensure that the fetch method returns a promise.

If your app does not contain any additional code, simply adding a return statement can resolve the problem:

fetch({app, store, route}) {
  return app.$axios.$get(`apps/${route.params.id}`)
    .then(res => {
      store.dispatch('setApp', {
      ...res,
      id: route.params.id
    })
    console.log(app.store.state.app);
  })
}

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

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...

CSS footer element refuses to disappear

This sample application features a header, footer, and a content div that includes a table displaying various statistics of basketball players. One issue I encountered was with the footer when there were many entries in the table. This caused the footer t ...

Can you please highlight parts of the text and provide dialogue with additional information?

I am currently enhancing my blog and looking for a way to implement JavaScript functionality that will help highlight specific parts of my text and provide additional information, like: I am currently working on my laptop When the user clicks on "lapto ...

Instructions for altering the hue of a canvas square when the cursor hovers over it

I want to implement a feature where the color of a tile changes when the user hovers their mouse over it, giving it a whitened effect. The tileset I am using consists of 32x32 tiles. Below are the scripts for reference. MAP.JS function Map(name) { ...

There seems to be an issue with the border displaying correctly within the div element

I am currently working on developing a tag input system, but I am encountering some CSS issues. What I am aiming for is to have a green border that surrounds and contains the 2 divs inside it, however, this is not happening as expected. You can see the fi ...

Using async/await with Fetch to send POST parameters for text/html content

Is there a way to POST parameters for content type text/html without sending it as an object? In my specific scenario, I need to include extra data that is not part of a form and is read from a cookie. When posting with body : {} or body: JSON.Stringify( ...

Implement a feature to dynamically load data as the user scrolls up, similar to the

I am in the process of creating a messaging platform and I am looking to implement a functionality where chat history is displayed upon scrolling up, similar to Facebook's chat system. Can anyone offer assistance with this task? ...

Execute the gulp module on the source files

Recently, I've been delving into the world of gulp and trying to enhance the readability of my js source files. I have a task in place (which executes successfully) that utilizes 'gulp-beautify' to beautify the js files: gulp.task('js& ...

Creating a Composite of Several Boxes in THREE.js

My goal is to display multiple boxes together in a specific structure shown in the image I have attached. I am interested in testing the GPU limitations by increasing the number of boxes, and then later on, I will focus on optimization. The framework I am ...

What is the best method for presenting nested JSON data in React using a key-value pair format?

This component serves as the product description section with tabs for both description and details. Selecting the description tab displays the product specifications in a tabular format. We are utilizing the Axios library to fetch JSON data from an API. I ...

Find the nth element of an array using Javascript's map function

Recently, I took on the challenge of learning Javascript independently and came across a rather complex task. I have an array with 18 labels and another 1D array containing all the values. Each label index corresponds to every nth element in the array. F ...

Is there a different method for looping in JSX besides .map()?

In my JSX code, I am attempting to display a specific value based on certain conditions. The current code snippet checks if the 'item.result' exists and has a length greater than 0. If so, it maps through the 'item.result' array and dis ...

Encountering a 500 error in Angular while utilizing forkJoin for calling API services

In my Angular 7 project, I have implemented a call in the ngOnInit method to two different API routes to fetch some data using forkJoin. Here is how I have set it up: ngOnInit() { debugger this.route.params.pipe( switchMap(params => for ...

Why is my code throwing an error stating "Unable to assign value to innerHTML property of null"?

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="container">Lorem ipsum</div&g ...

How to Implement Autocomplete Feature in Angular

CSS <div class="dropdown"> <input type="text" formControlName="itemName" (ngModelChange)="filterItems()" class="dropdown-input" (keyup)="onKeyPress($event)" (blur)="toggleDropdown(0)" (focus)="toggleDropdown(1)" placeholder="Search..." [ngCla ...

Implementing dynamic checkbox values depending on a selection from a dropdown menu in Angular

In my checkbox list, I have various Samsung mobile models and two offers available. $scope.offers = [ { id: "as23456", Store: "samsung", Offer_message:"1500rs off", modalname: "Samsung Galaxy You ...

Is there a way to eliminate the line that appears during TypeScript compilation of a RequireJS module which reads: Object.defineProperty(exports, "__esModule", { value: true });?

Here is the structure of my tsconfig.json file: { "compileOnSave": true, "compilerOptions": { "module": "amd", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "strictNullChecks": ...

What are the steps to switch to a root page after a successful sign-in with Ember-Auth?

After successfully implementing Ember-Auth using a pure token based approach, I am facing a challenge in redirecting users to the root of my app once they sign in. Although I know about actionRedirectable (refer to for details), since I am using a pure t ...

Upon loading the page, the menu automatically drops down for easy navigation

Currently, I am working on a WordPress site using the WallBase theme. You can check out a preview of the theme here. One issue I am facing is that when the page fully loads, the menu automatically drops down. I have tried various solutions to keep the me ...

How to build custom middleware with parameters in Node.js

I'm working on creating a middleware in nodejs for access levels, and I've written the following middleware: class AccessUser extends middlware { async AccessUser(access,req, res, next) { const getTokenFrom = (req) => { const autho ...