Home > Net >  Can't dispatch in mounted? vuex
Can't dispatch in mounted? vuex

Time:05-02

Does anyone know why my state.pages doesnt get filled with the json data I fetch with axios? However, when I change something in my file and save it, so that vite will reload, the data does show up on the page. And will dissapear again when I refresh the page in the browser.

PageView:

<template>
  <main v-if="page">
    <h1>{{ page.title }}</h1>
    <div  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;

CodePudding user response:

The race condition results because promises weren't correctly chained. As a rule of thumb, every function that uses promises should chain all promises in use and return a promise as a result of its work.

getPages is dispatched twice.

It should be:

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

And:

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