Unable to dispatch actions within the mounted lifecycle hook in Vuex?

Can anyone explain why the json data I fetch with axios is not populating my state.pages as expected? Interestingly, when I make a change to the file and vite reloads, the data appears on the page. However, it disappears again upon refreshing the browser.

PageView:

<template>
  <main v-if="page">
    <h1>{{ page.title }}</h1>
    <div class="content" v-html="page.content"></div>
  </main>
  <main v-else>
    <h1>loading</h1>
  </main>
</template>

<script>
import { mapGetters, mapActions } from "vuex";

export default {
  data() {
    return {
      page: null,
    };
  },
  methods: {
    ...mapActions({ getPages: "getPages" }),
  },
  computed: {
    slug() {
      return this.$route.params.slug;
    },

    getPage() {
      console.log(this.$store.state.pages);
      return (this.page = this.$store.state.pages.find(
        (page) => page.slug === this.slug
      ));
    },
  },
  mounted() {
    this.$store.dispatch("getPages");

    this.getPages();
    this.getPage;
  },
};
</script>

<style>
</style>

Vuex index:

import { createStore } from 'vuex';
import axios from 'axios';

const store = createStore({
  state() {
    return {
      pages: [],
    };
  },
  mutations: {
    setPages(state, { response }) {
      state.pages = response.data;
    },
  },
  actions: {
    getPages({ commit }) {
      axios.get('../src/data/pages.json').then((response) => {
        commit('setPages', { response });
      });
    },
  },
  getters: {},
});

export default store;

Answer №1

The issue of a race condition arises when promises are not properly chained together. It is crucial for any function utilizing promises to chain all promises and return a promise as the outcome of its execution.

getPages is called twice, causing an inconsistency.

Correct implementation should be:

getPages({ commit }) {
  return axios....

Furthermore:

  mounted() {
    return this.getPages()
    .then(() => {
      ...
    });
  },

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

Developing explosive Vue components consecutively

During my recent work on creating Vue components in a loop, I came across a strange issue with wires. for(let i=0;i<testInfo.length;i++) { $("#home").append("<lib_" + testInfo[i]['lib_id'] + "></lib_" + testInfo[i]['lib_id ...

How can Vue-toastr and Vue2 be configured with global options for toastr notifications?

I'm currently utilizing vue-toastr in my project, which combines Laravel 5.5 and Vuejs 2. Although the toasts are displaying correctly, I am struggling to set global options for them, such as position... I have attempted to do this but have been uns ...

The NodeJS environment is experiencing issues with async JavaScript functions returning undefined

I'm struggling to call a function that fetches data from an API, compares it with input, and should return either 0 or 1 for use in my code. However, the function is currently returning undefined. I can't seem to wrap my head around it. async fu ...

Transforming a function into its string representation | 'function(){...}'

func=function() {foo=true} alert(JSON.stringify(func)); alerts "undefined" obj={foo: true} alert (JSON.stringify(obj)); alerts: "{foo: true}" Have you ever wondered why JSON.stringify() doesn't work for a "function object"? It seems that when tryi ...

Reset the AJAX object using jQuery

Currently, my code looks like this: object1 = $.ajax({ .. .. }); If an error occurs, I would like to have the ability to restart the ajax request. For instance, if the user's connection is lost, I want to be able to easily call the same ajax again w ...

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

Utilizing a dictionary for comparing with an API response in order to generate an array of unique objects by eliminating duplicates

I currently have a React component that utilizes a dictionary to compare against an API response for address state. The goal is to map only the states that are returned back as options in a dropdown. Below is the mapping function used to create an array o ...

Ways to streamline the directives for conciseness?

This section contains a login field where users can input their username, password, and click the login button. It may seem lengthy and detailed at first glance. <form name='form' novalidate ng-submit="form.$valid && submit('/log ...

The publish-subscribe feature appears to be ineffective

Recently starting with meteor, I learned about the importance of removing autopublish. So, I decided to publish and subscribe to a collection in order to retrieve two different sets of values. Here is the code on my meteor side: Meteor.publish('chann ...

Upgrading from Vuetify 2 to 3 involves replacing the deprecated styles like .v-application, rounded, and flat with

I need help with upgrading from Vuetify/Vue 2 to Vue 3. I don't have much experience in front-end development, but I am responsible for updating some old code to keep things running smoothly. The migration guide is not very clear and assumes a certain ...

What is the best way to prevent a font awesome icon from appearing in a span during data loading

I am currently working on an Angular 11 application where I have implemented an icon to trigger the loading of a graph. However, I have noticed that there is a delay in loading the graph when the icon is clicked. To prevent users from triggering the icon m ...

I am experiencing some unwanted movement of divs when I hide one element and show another. Is there a way to prevent this from happening

My webpage features a dynamic div that transforms into another div upon clicking a button. Although both divs share similar properties, clicking the button causes some elements to shift unexpectedly. Strangely enough, when the height of the replacing div i ...

Navigating to the bottom of a specific element by scrolling

I am currently working on enhancing a module within the application I'm developing. The goal is to automatically scroll the browser window to the bottom of an element when said element's height exceeds the height of the window. The functionality ...

Tips for displaying user-entered information from a form after submitting it with PHP

How can I display the email in the email text input field with this code? It doesn't seem to work correctly when there is a failed login attempt. value= "if(isset($_POST['submit'])){ ?PHP echo $_POST[''email']?>"; ...

Transferring a DOM element to a different window while preserving event listeners in Internet Explorer 11

I am tasked with creating a webpage feature that allows users to detach a section of the page and move it to a new window on a second monitor, then reattach it back to the main page. The detached section must retain its state and event listeners during the ...

React Hook Form: When Submitting, Transform Date Object into String Date within an Array

Below is the data I am working with: { status: "Reserved", label: "Note", title: "Login Fragment - Navigation component With Coroutine", shareWith: "", notification_method: "Every Morning", notification_method_specific_time: Sat ...

Swapping values in JSON by comparing specific keys: A guide

I have JSON data that contains a key called reportData with an array of values: {"reportData":[ ["1185","R","4t","G","06","L","GT","04309","2546","2015","CF FE","01H1","20","23840","FF20"], ["1186","R","5t","R","01","L","TP","00110","1854","2016" ...

Error: Can't compile - Accordion controller is necessary

Encountered the following error in the console while using angular-bootstrap ui. My setup includes angular 1.2.6, bootstrap 3.0, and angular-bootstrap 0.10.0. Error: [$compile:ctreq] Controller 'accordion', required by directive 'accordionG ...

Use an Ajax call to "POST" and fetch the Jade layout for rendering

So, I have my own custom AJAX function. export function dynamicURL(obj) { $.ajax({ url: obj.url, type: 'post', data: obj.jade, dataType: 'JSON' }).done(function (ajaxReturn) { console.lo ...

What is the best way to retrieve JavaScript Values through Selenium?

Currently, I am working with Java selenium client and running this code snippet. The variable PAGE_NUMBER is assigned a value; however, when using selenium, I'm unable to retrieve it: String script = "var cellValue = selenium.browserbot.getUserWindow ...